Notice
Recent Posts
Recent Comments
Link
미새문지
Promise.all() 본문
728x90
Promise.all()
여러 개의 프로미스를 동시에 실행하고, 모든 프로미스가 완료될 때까지 기다리는 자바스크립트의 내장 메소드
주어진 프로미스 배열의 모든 프로미스가 성공적으로 이행되면 모든 결과를 배열로 반환하지만, 하나라도 거부되면 즉시 실패하며, 첫 번째 거부된 프로미스의 이유를 반환한다.
문법
Promise.all([promise1, promise2, promise3, ...])
.then(results => {
console.log(results); // 모든 프로미스의 결과가 배열로 반환
})
.catch(error => {
console.error(error); // 하나라도 실패하면 첫 번째 오류를 반환
});
동작 방식
- 입력: Promise.all()은 배열이나 이터러블 형태로 여러 개의 프로미스를 받는다.
- 병렬 실행: 모든 프로미스를 동시에 실행한다.
- 성공: 모든 프로미스가 성공하면 then()에서 모든 결과를 배열로 받는다.
- 실패: 하나라도 실패하면 catch()로 첫 번째 실패한 프로미스의 오류를 받는다.
예제
모든 프로미스가 성공하는 경우
const p1 = Promise.resolve(1);
const p2 = Promise.resolve(2);
const p3 = new Promise(resolve => setTimeout(() => resolve(3), 1000));
Promise.all([p1, p2, p3])
.then(results => {
console.log(results);
})
.catch(error => {
console.error(error);
});
p3이 1초 후에 출력되서 p1, p2, p3값인 1, 2, 3이 1초 후에 출력된다.
하나라도 실패하는 경우
const p1 = Promise.resolve(1);
const p2 = Promise.reject("에러 발생!");
const p3 = Promise.resolve(3);
Promise.all([p1, p2, p3])
.then(results => {
console.log(results);
})
.catch(error => {
console.error(error);
});
실패 시 에러 발생이 바로 출력되며, 에러 발생 메세지 외 다른 값은 출력되지 않는다.
async function fetchData() {
try {
const [user, post] = await Promise.all([
fetch("https://jsonplaceholder.typicode.com/users/1").then(res => res.json()),
fetch("https://jsonplaceholder.typicode.com/posts/1").then(res => res.json()),
]);
console.log("유저 정보:", user);
console.log("게시글 정보:", post);
} catch (error) {
console.error("데이터 가져오기 실패:", error);
}
}
fetchData();
async/await을 사용하면 then 없이 코드 작성이 가능
Promise.allSettled()
const p1 = Promise.resolve("성공 1");
const p2 = Promise.reject("실패 2");
const p3 = Promise.resolve("성공 3");
Promise.allSettled([p1, p2, p3])
.then(results => console.log(results));
allSettled()를 사용하면 모든 프로미스의 상태를 반환하기 때문에 실패한 이유를 확인할 수 있다.
728x90
'개발 TIL' 카테고리의 다른 글
퍼즐 만들기 (0) | 2025.02.13 |
---|---|
디바운스(Debounce), 쓰로틀(Throttle) (0) | 2025.01.31 |
이벤트 전파(event propagation), 웹 성능 최적화 방법 (0) | 2025.01.31 |
CommonJS와 ES Module의 차이점 (0) | 2025.01.29 |
async와 defer의 차이점 (0) | 2025.01.28 |