Categories
interview

Promise.all() polyfill

Javascript

Promise.alll = promises => new Promise((resolve, reject) => {
  let count = 0;
  const responses = [];
  promises.forEach((promise, index) => {
    promise.then((response) => {
      responses[index] = response;
      if (++count === promises.length) {
        resolve(responses);
      }
    }).catch(reject);
  })
});

const promise1 = Promise.resolve(3);
const promise2 = Promise.resolve(6);
const promise3 = Promise.resolve(9);
Promise.alll([promise1, promise2, promise3]).then((values) => {
  console.log(values);
}).catch((error) => {
  console.log(error);
});

Output

[3, 6, 9]

Demo