ES6

Promise.all Polyfill

polyfill promise all

polyfill promise all

The Promise.all() method returns a single promise that fulfills when all of the promises passed as an iterable have been fulfilled or it rejects with the reason of the first promise that rejects.

Now let’s try to implement the same behaviors as stated in the definition above.

1st step: is to create a method with an array of promises as parameters.

Promise.all = function(promises) { }

2nd step: Now we will create an empty array named as results which we will be using to store the results of promise array.

3rd step: As we know Promise.all returns a new single Promise, so we need to create a new promise and return it as:

  return new Promise((resolve, reject) => { });

4th Step: Now we should check if the promise array has at least 1 element, if not then return an empty array of results as:

// check if array has any promise
if (!promises.length) {
  resolve(results);
  return;
}

5th Step: Now we know array has at least 1 promise so we will loop over each promise and then using .then() and .catch() will check if it’s fulfilled or rejected.

  • If it’s fulfilled then we will add the result of that particular promise to the results array. Also when we react to last promise we will resolve our promise with the results array.
.then((result) => {
  results.push(result);
  if (index === promises.length - 1) {
    resolve(results);
  }
});
  • If it’s rejected then we will simply reject our promise
.catch((err) => reject(err));

So our final polyfill looks like this now:

Promise.all = function(promises) {
  let results = [];
  return new Promise((resolve, reject) => {
    promises.forEach((p, index) => {
      p.then((result) => {
        results.push(result);
        if (index === promises.length - 1) {
          resolve(results);
        }
      }).catch((err) => reject(err));
    });
  });
};

Below is the live code for the polyfill of Promise.all()

Let me know your thoughts

%d bloggers like this: