ES6 자바스크립트 Promise에 대한 이해
1. Promise의 Output
Promise는 성공(Success) 또는 실패(Failure) 두 가지 결과를 가질 수 있습니다.
2. then 및 catch 사용
then
: 작업이 성공하면 호출되며, 성공 상황에 대한 동작을 지정합니다.
catch
: 작업이 실패하면 호출되며, 실패 상황에 대한 동작을 지정합니다.
3. Unhandled Promise Rejection Error
Promise가 실패한 경우 해당 거부를 처리할
.catch()
또는 .then()
메서드가 없다면 'Unhandled Promise Rejection' 에러가 발생합니다. 모든 Promise 체인에는 적절한 오류 처리를 위한 catch 핸들러가 필요합니다.예시 코드
javascriptCopy code
// Promise 생성
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
const success = true;
if (success) {
resolve("Success!"); // 성공 시 호출
} else {
reject("Failure!"); // 실패 시 호출
}
}, 2000); // 2초 후에 작업 완료
});
// Promise 사용
myPromise
.then((result) => {
console.log("Success:", result); // 성공 시 동작
})
.catch((error) => {
console.error("Error:", error); // 실패 시 동작
});
Promise 체인에서의 실패 처리
javascriptCopy code
someAsyncFunction()
.then(result => {
console.log("First step:", result);
return anotherAsyncFunction();
})
.then(anotherResult => {
console.log("Second step:", anotherResult);
return yetAnotherAsyncFunction();
})
.then(yetAnotherResult => {
console.log("Third step:", yetAnotherResult);
})
.catch(error => {
console.error("Error in fourth step:", error);
throw error;
})
.then(fifthResult => {
console.log("Fifth step:", fifthResult);
return finalAsyncFunction();
})
.then(finalResult => {
console.log("Sixth step:", finalResult);
})
.catch(error => {
console.error("Error in seventh step:", error);
throw error;
});
Promise.all에 대한 이해
1. 개요
Promise.all은 여러 개의 프로미스를 동시에 처리하고, 모든 프로미스가 이행될 때까지 기다린 후 그 결과를 반환하는 메서드입니다.
2. 동작 원리
- Promise.all에 전달된 모든 프로미스가 이행될 때까지 기다립니다.
- 하나의 프로미스라도 거부될 경우, 첫 번째로 거부된 프로미스의 이유와 함께 즉시 거부됩니다.
- 모든 프로미스가 성공적으로 이행되면, 해당하는 각 프로미스의 결과가 배열 형태로 반환됩니다.
3. 예시 코드
javascriptCopy code
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => resolve('Promise 1 resolved'), 1000);
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(() => resolve('Promise 2 resolved'), 2000);
});
const promise3 = new Promise((resolve, reject) => {
setTimeout(() => resolve('Promise 3 resolved'), 3000);
});
Promise.all([promise1, promise2, promise3])
.then(results => {
console.log('All promises resolved:', results);
})
.catch(error => {
console.error('At least one promise rejected:', error);
});
4. 설명
- 위 예시에서는 세 개의 프로미스를 생성하고 각각 1초, 2초, 3초 후에 이행됩니다.
- Promise.all 메서드는 프로미스 배열을 받아 각 프로미스가 모두 이행될 때까지 기다립니다.
- 세 개의 프로미스가 모두 성공적으로 이행되면, 각 프로미스의 결과가 배열 형태로 반환되어
.then()
블록으로 전달됩니다.
- 모든 프로미스가 성공하면 결과는 **
['Promise 1 resolved', 'Promise 2 resolved', 'Promise 3 resolved']
*와 같이 출력됩니다.
5. 주의 사항
- Promise.all은 모든 프로미스를 병렬로 처리하므로, 모든 작업이 동시에 진행됩니다.
- 만약 프로미스 중 하나라도 거부될 경우, Promise.all은 즉시 거부됩니다. 따라서 모든 프로미스가 성공해야 하는 작업에 사용되어야 합니다.
- Promise.all에 전달된 프로미스 배열이 비어있거나 존재하지 않는 경우, 즉시 이행됩니다.
Share article