promise.all 구현하기

00_8_3·2022년 8월 23일
0

promise.all을 구현해보기

ECMAScript spec에 써 있기를

This function returns a new promise which is fulfilled with an array of fulfillment values for the passed promises, or rejects with the reason of the first passed promise that rejects. It resolves all elements of the passed iterable to promises as it runs this algorithm.

번역하자면 모든 Promise가 이행되었을 때 배열로 이행된 결과를 알려주거나 Promise 중 하나라도 실패 시 이유와 함께 reject 됩니다.

PromiseAll 구현코드

const PromiseAll = (promises = []) => {
  return new Promise((rs, rj) => {
    let count = promises.length;
    const returnArray = [];
    promises.forEach((ps, index) => {
    console.log(index);
      Promise.resolve(ps)
        .then((value) => {
          returnArray[index] = value;
          --count;
          !count && rs(returnArray);
        })
        .catch(rj);
    });
  });
};

const p1 = new Promise((resolve) => {
  setTimeout(() => resolve(3000), 3000);
});

const p2 = new Promise((resolve) => {
  setTimeout(() => resolve(2000), 2000);
});

const p3 = Promise.reject(1000);

/* PromiseAll([p1, p2]).then(console.log); // [3000, 2000] */  // * 1
PromiseAll([p1, p2, 3]).then(console.log); // [3000, 2000, 3]			// * 2
/* console.log(PromiseAll([p1, p2, p3])); // Error 1000 */	// * 3

설명

  • PromiseAll의 파라미터를 Promise로 간주하여 Promise.resolve 해준다.

  • 입력받은 promise 배열을 개수를 promise 상태가 fulfilled 될 때 마다 -1 씩 카운트 한다.

    • 개수가 총 3개인 경우 count가 0이 된 순간이 모든 promise가 이행되었음을 알 수 있음.
  • forEach는 순차인데 어떻게 동시성을 보장해주나요?

    mdn의 문서에 따르면 forEach의 경우 Promise 결과를 기다려 주지 않습니다. 그렇기 때문에
    Promise들이 모두 task 큐에 들어가 결과의 동시성을 갖을 수 있습니다.

Promise.all의 성능

https://itnext.io/high-performance-node-js-concurrency-with-events-on-hexomter-da4472ae3061

출처

https://velog.io/@jay/implement-promise-all

https://tc39.es/ecma262/#sec-promise.all

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

0개의 댓글