나만보는개발공부블로그

How to use map or forEach ES6 with async and await. 본문

Javascript&Typescript

How to use map or forEach ES6 with async and await.

alexrider94 2022. 9. 17. 13:24

async/await문법을 map과 forEach에서 사용하게 될 경우 내가 원하는 흐름처럼 작동하지 않을것이다.

forEach나 map을 통해 루프를 진행할경우 병렬이기 때문에 await을 기다리지 않고 function내의 로직만 처리하기 때문이라고 한다.

예시코드

let slugs = [];

const batches = lodash.chunk(libraries, 50);

batches.map(async (batch) => {
  //this will return Promise
	return await batch.something();
})

해결방안

//Reading in sequence
for(const batch of batches) {
	await batch.something();
}

//Reading in parallel
await Promise.all(batches.map((batch)=>{
	return await batch.something();
}));


Babel을 통해 async/await를 변환해 생기는 코드에는 generator function(1) 이 생기고 forEach를 사용하면 각 반복 구간마다 생기는 generator function(n)과는 아무 관련이 없을것이다. 그래서 그것들은 독립적으로 실행될 것이고 기다리지 않게 되는것이다. 그리고(n)들과의 generator.prototype.next() 컨텍스트가 없어서 내가 원하는대로 동작하지 않는것이다.


변환 예시

async function foo() {
  await bar();
}

---------------------------------------------

var _asyncToGenerator = function (fn) {
  ...
};
var foo = _asyncToGenerator(function* () {
  yield bar();
});

'Javascript&Typescript' 카테고리의 다른 글

For ... in 과 For ... of 반복문  (0) 2023.09.13
함수형 컴포넌트의 제너릭 타입 설정.  (0) 2021.12.04
Splice()  (0) 2021.06.17
Shallow Copy & deep Copy  (0) 2021.03.23
Hoisting  (0) 2021.03.04