병렬 실행이 await을 기다려주지 않는 이유
현우
- 프론트엔드
- 자바스크립트
12345678async function run() {
const items = [1, 2, 3];
items.forEach(async (item) => {
await processItem(item);
});
console.log("완료");
}123456789function forEach(callback) {
for (let i=0; i<array.length; i++) {
callback(array[i]);
}
}
callback(1); // Promise 반환, 무시
callback(2); // Promise 반환, 무시
callback(3); // Promise 반환, 무시123const results = items.map(async (item) => {
return await processItem(item);
});123456789101112const results = await Promise.all(
items.map(async (item) => {
return await processItem(item);
});
);
processItem(1); // 시작
processItem(2); // 시작
processItem(3); // 시작
// 모두 완료될 때까지 대기
// 최종 results 반환1234// 상위에 await이 정의된 상태라고 가정합니다.
for (const item of items) {
await processItem(item);
}123await Promise.all(
items.map((item) => processItem(item));
);12345async function run() {
for (const item of items) {
await processItem(item);
}
}1234567891011121314151617181920async function run() {
console.log("반복 시작");
for (const item of [1, 2, 3]) {
await delay(1000);
console.log(item);
}
console.log("반복 종료");
}
run();
console.log("다른 코드");
// 반복 시작
// 다른 코드
// 1
// 2
// 3
// 반복 종료방식 | await 사용 가능 여부 | 전체 완료 대기 | 실행 방식 |
for | 가능 | 가능 | 가능 |
for .. of | 가능 | 가능 | 순차 |
while | 가능 | 가능 | 순차 |
do .. while | 가능 | 가능 | 순차 |
forEach(async () ⇒ {}) | 콜백 내부에서는 가능 | 불가능 | 사실상 동시 실행 |
map(async () ⇒ {}) | 콜백 내부에서는 가능 | 배열만으로는 불가능 | Promise 배열 생성 |
Promise.all(map(...)) | 가능 | 가능 | 병렬 |
for await .. of | 가능 | 가능 | 비동기 이터러블 순회 |