map() and Promise.all()

zenibako.lee
3 min readApr 15, 2020

--

javascript

이번 글은

2중 array 구조를 가진 객체의 최하위 멤버를
비동기 작업단위로 나누어
처리하고,
비동기 작업을 하나로 묶어 동기적으로 관리하기 위한 방법을 설명합니다.

let a = [1,2,3]
let b = [4,5]
let c = [6,7,8]
let arr = [a,b,c] // arr은 2중 array입니다.

array내부의 array의 멤버 각각을 이용해 만들 비동기 함수는

아래와 같습니다.

const asyncFunc = async (n) =>{
console.log('out',n)
return await new Promise((resolve)=>setTimeout(((n)=>{console.log(n);resolve(n)}).bind(null,n),n*1000))
}

setTimeout 메소드에 n을 bind해주는 것은
이벤트루프 과정에서 ‘this’ context를 상실하기 때문입니다.

해당 함수에 2를 넣었을 경우, 2초뒤 2라는 값을 return하게 됩니다.

await Promise.all(arr.map((innerArr)=>{
return Promise.all(innerArr.map(
async(num)=>{return await asyncFunc(num)}
))
}))
console.log('after array asyncFuncs')

Promise.all() 은 비동기함수들의 array를 인자로 받아,
해당 함수들을 실행시키는 메소드 입니다.

실행의 return type은 Promise객체이므로
await를 앞에 붙여 동기적으로 실행되도록 할 수 있습니다.

이제 작성한 코드들을 돌려보도록 하겠습니다.

그 결과 어레이의 멤버를 이용해 만든 setTimeout 비동기 함수들이 차례대로 스택에 쌓이고, 순차적으로 이벤트루프를 종료 후,
모든 콜백함수(console.log)가 실행되고 나서
‘after array asyncFuncs’가 출력이 됩니다.

--

--

zenibako.lee
zenibako.lee

Written by zenibako.lee

backend engineer, JS, Node, AWS

No responses yet