[Javascript] map/foreach에서 async/await 사용할 때 주의할 점

Hoony·2022년 1월 8일
0

비동기함수를 처리함에 있어 async/await을
Array.map이나 foreach문을 사용하면 안된다.

for vs Array.map

for문과 map을 비교하여 보자.
간단하게 1초 후 전달받은 파라미터를 console.log() 하는 함수가 있다.

const list = [1, 10, 100];
const test = async (element) => {
	new Promise((resolve, reject) => {
    	setTimeout(() => {
        	console.log(element);
            resolve();
        }, 1000)
    })
}

list.map(async(element) => {
	await test(element);
})
console.log('DONE - map');

for(let i = 0; i < list.length; i++) {
	await test(list[i]);
}
console.log('DONE - for')

결과는 아래와 같다.

DONE - map
1
10
100
1
10
100
DONE - for

결과적으로
Array function인 map과 forEach는
async function을 await해주지 않는다.

동기적으로 처리할 일이 있다면 for문을 써야한다.

forEach / map 더 자세히 알아보기

  • 두 함수의 차이점은 값을 return 하느냐(map) 안하느냐(forEach)의 차이가 있다.
  • 두 함수의 공통점은 outer context(map 자체)와 inner context(실행주체)가 따로 존재한다.

두 번째 이야기를 for문으로 쉽게 풀어 보면 아래와 같다.

arr.map(async() => {
  	await funA();
});

위 형태가 아래와 같이 실행된다고 보면 된다.
(이해를 위한 설명, 실제로는 다르다.)

for (let i = 0; i < arr.length; i++) {
	(async () => await funcA())(); 
}

따라서 map 안에서 async/await을 하여도 적용되지 않고,
for문의 break/continue 도 사용할 수 없다.

profile
아는 만큼 보인다

0개의 댓글