상식닷컴
로그인
가입하기
2026년 상식닷컴 선정 식당 & 카페 리스트
2025년 2026년 신상 호텔 리스트
최근에 오픈한 호텔을 찾는다면 살펴보세요
일주일 식단표 어플
자동 일주일 식단표 어플
안드로이드
아이폰
주식 & 코인 차트의 신
1000만원으로 2000만원 만들기 프로젝트
수정하기 - 비동기 프로그래밍에서 'promise'의 활용 사례는 무엇인가요?
닉네임
비밀번호
제목
내용
[이미지 업로드는 권한이 있는 사람만 가능. 하단 카톡으로 연락]
비동기 프로그래밍에서 'p<a href='https://sangseek.com/sangseeks/romise/ko'>romise</a>'는 비동기 작업의 완료 또는 실패를 나타내는 객체로, JavaScript와 같은 언어에서 널리 사용됩니다. Promise는 비동기 작업의 결과를 다루는 데 있어 코드의 가독성을 높이고, 콜백 <a href='https://sangseek.com/sangseeks/지옥/ko'>지옥</a>(callback hell)을 피할 수 있는 방법을 제공합니다. 다음은 Promise의 활용 사례에 대한 자세한 설명입니다. 1. API 호출 가장 일반적인 Promise의 활용 사례 중 하나는 외부 API를 호출하는 것입니다. 예를 들어, 웹 애플리케이션에서 사용자 정보를 가져오기 위해 REST API를 호출할 때 Promise를 사용할 수 있습니다. ```javascript function fetchUserData(userId) { return new Promise((resolve, reject) => { fetch(`https://api.example.com/users/${userId}`) .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }) .then(data => resolve(data)) .catch(error => reject(error)); }); } fetchUserData(1) .then(user => console.log(user)) .catch(error => console.error('Error fetching user data:', error)); ``` 위의 예제에서 `fetchUserData` 함수는 Promise를 반환하며, API 호출이 성공하면 사용자 데이터를 resolve하고, 실패하면 reject합니다. 이를 통해 호출자는 `.then()`과 `.catch()`를 사용하여 결과를 처리할 수 있습니다. 2. 파일 읽기 Node.js와 같은 환경에서는 파일 시스템에 접근할 수 있습니다. 파일을 비동기적으로 읽을 때 Promise를 사용하여 코드의 가독성을 높일 수 있습니다. ```javascript const fs = require('fs').promises; function r<a href='https://sangseek.com/sangseeks/eadFile/ko'>eadFile</a>Async(filePath) { return fs.readFile(filePath, 'utf-8') .then(data => { console.log('File content:', data); return data; }) .catch(error => { console.error('Error reading file:', error); throw error; }); } readFileAsync('example.txt') .then(content => { // 파일 내용 처리 }) .catch(error => { // 오류 처리 }); ``` 이 예제에서는 `fs.promises`를 사용하여 파일을 비동기적으로 읽습니다. Promise를 사용함으로써 파일 읽기 작업이 완료된 후의 처리를 쉽게 할 수 있습니다. 3. 여러 비동기 작업 처리 Promise는 여러 비동기 작업을 동시에 처리할 때 유용합니다. `<a href='https://sangseek.com/sangseeks/Promise.all/ko'>Promise.all</a>()` 메서드를 사용하면 여러 개의 Promise를 동시에 실행하고, 모든 작업이 완료될 때까지 기다릴 수 있습니다. ```javascript function fetchDataFromMultipleSources() { const api1 = fetch('https://api.example.com/data1'); const api2 = fetch('https://api.example.com/data2'); const api3 = fetch('https://api.example.com/data3'); return Promise.all([api1, api2, api3]) .then(responses => Promise.all(responses.map(res => res.json()))) .then(data => { console.log('All data:', data); return data; }) .catch(error => { console.error('Error fetching data:', error); }); } fetchDataFromMultipleSources(); ``` 위의 코드에서는 세 개의 API를 동시에 호출하고, 모든 응답이 완료될 때까지 기다립니다. 모든 데이터가 성공적으로 수신되면, 이를 처리할 수 있습니다. 4. 순차적 비동기 작업 Promise를 사용하면 비동기 작업을 순차적으로 실행할 수 있습니다. `.then()` 체이닝을 통해 이전 작업의 결과를 다음 작업에 전달할 수 있습니다. ```javascript function <a href='https://sangseek.com/sangseeks/processData/ko'>processData</a>() { return fetchUserData(1) .then(user => { console.log('User data:', user); return fetchUserPosts(user.id); }) .then(posts => { console.log('User posts:', posts); return fetchPostComments(posts[0].id); }) .then(comments => { console.log('Comments for the first post:', comments); }) .catch(error => { console.error('Error during processing:', error); }); } processData(); ``` 이 예제에서는 사용자 데이터를 가져온 후, 해당 사용자의 게시물과 댓글을 순차적으로 가져옵니다. 각 단계에서 발생할 수 있는 오류를 catch 블록에서 처리할 수 있습니다. 5. UI 업데이트 비동기 작업의 결과에 따라 UI를 업데이트하는 경우에도 Promise를 활용할 수 있습니다. 예를 들어, 데이터를 가져온 후 화면에 표시할 수 있습니다. ```javascript function loadUserProfile(userId) { fetchUserData(userId) .then(user => { document.getElementById('username').innerText = user.name; return fetchUserPosts(user.id); }) .then(posts => { const postsContainer = document.getElementById('posts'); posts.<a href='https://sangseek.com/sangseeks/forEach/ko'>forEach</a>(post => { const postElement = document.createElement('div'); postElement.innerText = post.title; postsContainer.appendChild(postElement); }); }) .catch(error => { console.error('Error loading user profile:', error); }); } loadUserProfile(1); ``` 이 예제에서는 사용자 프로필을 로드하고, 사용자 이름과 게시물을 UI에 업데이트합니다. Promise를 사용하여 비동기 작업의 결과를 쉽게 처리할 수 있습니다. 결론 Promise는 비동기 프로그래밍에서 매우 유용한 도구로, 코드의 가독성을 높이고, 비동기 작업의 결과를 효과적으로 관리할 수 있게 해줍니다. API 호출, 파일 읽기, 여러 비동기 작업 처리, 순차적 작업 실행, UI 업데이트 등 다양한 상황에서 Promise를 활용할 수 있습니다. 이러한 특성 덕분에 Promise는 현대 웹 개발에서 필수적인 개념으로 자리 잡고 있습니다.
이용안내
커뮤니티 이용안내
×
- 게시한 게시글로 발생하는 문제는 게시자에게 책임이 있습니다.
- 게시글이 타인/타업체의 저작권을 침해할 경우 모든 책임은 게시자에게 있습니다. 게시자가 모든 손해를 부담해야 합니다.
- 상식닷컴 운영자는 게시자와 상의하지 않고 게시글을 수정 또는 삭제할 수 있습니다.
- 상식닷컴 운영자는 깨끗한 커뮤니티 공간을 만드는 것이 1순위입니다.
수정하기
취소하기