320x100
320x100

forEach의 동작 원리

Array.prototype.forEach = function (callback) {
  for (let index = 0; index < this.length; index++) {
    callback(this[index], index, this);
  }
};

: 배열 요소를 돌면서 callback을 실행할 뿐, 한 callback이 끝날때까지 기다렸다가 다음 callback을 실행하는 것이 아니다

 

 

 

 

 

비동기 작업 순차처리

async function asyncForEach(array, callback) {
  for (let index = 0; index < array.length; index++) {
    const result = await callback(array[index], index, array);
    console.log(result)
  }
}

 

: for 또는 for of, for in을 사용하여 반복문 내에서 await로 함수를 호출

: 각 결과를 await할 수 있으며, 순차적으로 처리할 수 있다

 

 

 

 

 

 

비동기 작업 병렬처리

: 실행 순서가 중요하지 않을때 유용

const target_url = ["ur11", "ur12", "url3"];

// 다운로드에 약 1초가 걸리는 비동기 함수라고 가정
function async_download(url) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log(url);
            resolve();
        }, 1000);
    });
}

async function parallel(array) {
    const promises = array.map((url) => async_download(url));
    await Promise.all(promises);
    console.log("all done :)");
}

parallel(target_url);

: forEach와 달리 모든 작업이 완료되고나서 다음 코드를 실행한다

: 그러나 하나라도 실패할 경우 로직 실패처리를 띄운다

 

- 중요한 부분

// 반복적인 네트워크 호출 함수를 가진 Arr 객체 배열의 함수들을 병렬실행 
const promises = Arr.map(async (v) => await v.execute() )

 

 

 

 

 

 

 

 

Reference

 

배열에 비동기 작업을 실시할 때 알아두면 좋은 이야기들

프론트엔드 인턴 면접에서 비동기 작업 관련 질문 대답 못한 뒤 외양간 뚝딱뚝딱 고치는 이야기.

velog.io

 

Promise를 이용한 비동기 순차 처리와 병렬 처리 핸들하기 | 아웃풋 트레이닝

Array.prototype.reduce를 이용한 방식과 Promise.all/Promise.allSettled 방식은 프로미스 처리에 있어 중요한 차이점을 가지고 있다. 어떤 방식을 선택할지 결정하기 전에 각 방식의 특성을 이해하고 사용 사

baek.dev

 

300x250
728x90