DEV/javascript
Javascript Promise 동시에 여러 개 실행하기
석봉
2022. 4. 8. 16:59
Javascript Promise 동시에 여러 개 (한번에 여러 개) 실행하는 방법
Promise.all(배열) : 하나라도 실패하는 경우 catch로 감.
기본적인 사용 방식
const promise1 = Promise.resolve('성공1');
const promise2 = Promise.resolve('성공2');
Promise.all([promise1, promise2])
.then((result) => {
console.log(result); // ['성공1', '성공2']
});
...
요청을 한번에 묶고 모든 요청에 대해 응답이 완료된 후 실행하는 방법.
// @param {Array} api_url 조회 대상(API url) 묶음
async function getApi(api_url) {
const promises = [];
// ticket의 comments 조회
api_url.forEach((url) => {
let target = `/api/${url}`; // 본인 api 주소에 맞게 수정
const delayedCall = async () => { return apiReq(target); } // api를 요청하는 함수
promises.push(delayedCall());
});
await Promise.all(promises).then((res) => {
// 모든 요청을 시도하고 모든 요청이 반환된 경우 해당 코드 실행...
});
return attachments;
}
async function apiReq(target) {
// 코드작성...
}
Promise가 궁금하다면...?
https://seokbong.tistory.com/56
Javascript Promise 정리 (설명을 경량화...)
오늘은 Promise를 찾아보았다. 검색을 해보니...? Promise 객체는 비동기 작업이 맞이할 미래의 완료 또는 실패와 그 결과 값을 나타냅니다. - https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference..
seokbong.tistory.com