JavaScript Bazzi : Promise.all()

JavaScript Bazzi : Promise.all()

ยท

2 min read

Welcome to JavaScript baazi a blog series where we go through common interview questions in JavaScript and understand everything around them.

Firstly What is Promise.all() ?

So... Promise.all() take an array of promises as input and then return a promise that resolves to an array of the result of input promises. For example, we have the following 3 promises...

let promise1 = Promise.resolve(5);
let promise2 = 30;
let promise3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, "meow");
});

Now we can pass them as an array into Promise.all()

Promise.all([promise1, promise2, promise3]).then((values) => {
  console.log(values);
});

this will resolve into

 [5, 30, 'meow']

Okay, what if a promise is rejected ?? what will happen then ?? let's check that out...

let promise1 = Promise.resolve(5);
let promise2 = 30;
let promise3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, "meow");
});

let promise4 = new Promise((relove, reject) => {
  reject("server not responded");
});
Promise.all([promise1, promise2, promise3 ,promise4]).then((values) => {
  console.log(values);
});
//

This will result in...

Screenshot 2022-04-05 at 6.28.55 PM.png so now we know that.. any of the promises does not resolve promise.all() will not resolve instead it will throw that error. So now we can fire up our terminal and get started :)

Firstly we need to make a function :) that's obvious... and it will take an array as an argument. then it will iterate through all the promises in that array and will store the result of them somewhere and will return it when all promises have been iterated. And there is one more thing... we need to throw an error when the promise does not resolve....

function promiseAllPolyFill(listOfPromises) {
  return new Promise((resolve, reject) => {
// array result to store the resolved value from the promises...
    let result = [];
// promise completed to count number of completed promises
    let promiseCompleted = 0;

    listOfPromises.forEach((value, index) => {

      Promise.resolve(value)
        .then((val) => {
          result[index] = val;
          promiseCompleted += 1;

          if (promiseCompleted === listOfPromises.length) {
            resolve(result);
          }
        })
// if promise doesn't get resolved we need to throw error
        .catch((error) => {
          reject(error);
        });
    });
  });
}
promiseAllPolyFill([promise1, promise2, promise3]).then((values) => {
  console.log(values);
});

and here is the output... it works ๐Ÿฑ๐Ÿฑ๐Ÿฑ๐Ÿฑ

Screenshot 2022-04-05 at 10.57.20 PM.png

Did you find this article valuable?

Support Gaurav Tewari by becoming a sponsor. Any amount is appreciated!