250x250
Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | ||||||
| 2 | 3 | 4 | 5 | 6 | 7 | 8 |
| 9 | 10 | 11 | 12 | 13 | 14 | 15 |
| 16 | 17 | 18 | 19 | 20 | 21 | 22 |
| 23 | 24 | 25 | 26 | 27 | 28 | 29 |
| 30 |
Tags
- create-next-app
- 리액트네이티브
- Jest uuid syntax
- 테이블 해시 함수
- 중첩 점
- 호텔 대실
- 구름톤 챌린지
- Leetcode #javascript #알고리즘 #Algorithms #js
- mutationobserver
- nextjs
- Google 애널리틱스
- 구름톤
- 최솟갑 구하기
- nextjs-performance
- 연결 요소 제거하기
- 과제 진행하기
- ResizeObserver
- 테스트 Date
- 자바스크립트
- JavaScript
- 귤 고르기
- 날짜 테스트
- Hermes Engine
- 헤르메스 엔진
- jest
- 구름톤챌린지
- 프로그래머스
- 통신망분석
- 리액트네이티브 엔진
- mock date
Archives
- Today
- Total
나만보는개발공부블로그
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:24async/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 |