현재 블로그에서도 Promise.all()를 사용해 데이터를 불러오고 있어 공부 겸 정리해보았다.
Promise.all()
- Promise.all() 은 여러 개의 Promise 들을 비동기적으로 실행하여 처리할 수 있다.
- Promise.all() 은 여러 비동기 태스크를 동시에(병렬적으로) 실행하고, 가장 마지막 태스크가 완료될 때 완료 상태의 프라미스를 반환합니다.
- Promise.all() 은 여러 개의 Promise 들 중 하나라도 reject 를 반환하거나 에러가 날 경우, 모든 Promise 들을 reject 시킨다.
- Promise.all 내부에서는 태스크들의 순서가 제어되지 않기 때문에, 태스크의 순서가 중요한 경우라면 절대로 Promise.all을 통해 관리해서는 안된다.
const foodList = [
{ name: 'cake', id: 1 },
{ name: "juice", id: 2 },
{ name: 'coke', id: 3 }
];
const getFoodById = async (id) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
const [food] = foodList .filter(food=> food.id === id)
resolve(food)
}, 1000)
})
}
const getAllFoods = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(foodList)
}, 2000)
})
}
const fetchData = async () => {
// Promise.all() 은 실행할 비동기 태스크들이 담긴 배열을 인자로 받는다.
const [food, foodList] = await Promise.all([getFoodById(2), getAllFoods()])
console.log(food)
console.log(foodList)
}
fetchData()
참고
Promise.all() - JavaScript | MDN
The Promise.all() static method takes an iterable of promises as input and returns a single Promise. This returned promise fulfills when all of the input's promises fulfill (including when an empty iterable is passed), with an array of the fulfillment valu
developer.mozilla.org
'Javascript' 카테고리의 다른 글
형제, 부모, 자식 노드 접근 (1) | 2024.08.28 |
---|---|
HTML 태그(DOM) 접근하기 (0) | 2024.08.28 |
문서의 로딩되는 시점 이벤트 제어하기 (0) | 2024.08.27 |
배열 reduce() 사용법 및 예제 (0) | 2024.08.26 |
input checkbox 하나만 선택 (0) | 2024.08.26 |