How to use JavaScript Promise.all with realtime 
code example [Axios GET Calls]

How to use JavaScript Promise.all with realtime code example [Axios GET Calls]

Promise.all()

What is Promise.all

A Promise.all() is a static method that takes an array (group) of promises as input and does the process as a single promise and return in than-able or catch.

The basic syntax of Promise.all is

  Promise.all([promise1, promise2,.....])
   .then(result=>{
     //Congrats! The promise got resolved.
    }).catch(err=>{
     //Ohh ! The promise got rejected.
    })

where promise1, and promise2 are async functions that also return a promise.

When to use Promise.all method

When you have a group of asynchronous tasks to process in a single shot then it's recommended to use Promise.all().

To understand clearly let's take an example of async functions which is getting resolved by the Promise.all() function.

const p1 = new Promise((resolve,reject)=>{
    setTimeout(()=>{
        resolve('p1 completed');
    },1000);
})

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

const p3 = new Promise((resolve,reject)=>{
    setTimeout(()=>{
        resolve('p3 completed');
    },3000);
})

Promise.all([p1,p2,p3,])
    .then(result=>{
        console.log(result);
    }).catch(err=>{
        console.log(err);
    })

Results returned from the above code snippet

[ 'p1 completed', 'p2 completed', 'p3 completed' ]

In the above example we can see that p1,p2 and p3 are the async functions because it's having setTimeout as a function so each function will be resolved respectively after 1,2 and 3 seconds but Promise.all will resolve once the last function will be resolved that's the beauty of the Promise.all() method.

The core property of Promise.all() method is that It will resolve all function and returns result in the same order in which order we have given input functions array.

If all array functions (p1,p2,p3) will resolve then only it will give a result in then-able. Otherwise, if any one of the Promise function gets rejected for any reason then the Promise.all() method will go into catch() block. you can see the below example for this scenario.

 const p1 = new Promise((resolve,reject)=>{
    setTimeout(()=>{
        resolve('p1 completed');
    },1000);
})

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

const p3 = new Promise((resolve,reject)=>{
    setTimeout(()=>{
        reject(new Error('p3 rejected'));
    },3000);
})


Promise.all([p1,p2,p3,])
    .then(result=>{
        console.log(result);
    }).catch(err=>{
        console.log(err);
    })

This code snipped will be coming in the catch block

Error: p3 rejected

Now let's see the real-time example of Promise.all().

Suppose you have a dashboard where you have to call 3 APIs Till the time API is calling you to have to show loader on the screen. So you can achieve this very easily by using Promise.all() method. Please refer to the below example

const axios = require('axios');

const task = async (id)=>{
    const response = await axios(`https://reqres.in/api/users/${id}`);
    const {data} = response;
    return data.data;
}
const ids = [1,2,3];
const allTasks = ids.map((pageNumber)=>{
    return task(pageNumber);
});

// you can start page loader here
Promise.all(allTasks)
    .then((result)=>{
        console.log(result);
        // once the task is finished then you stop the loader over here
    }).catch((err)=>{
        //If error comes then also you have to stop the loader
        console.log(err);
    })

In the above example, I have created a function called 'task' which async function basically calling the API.

So we have to call 3 API for UserID 1,2 and 3 so for that we have grouped 3 APIs calls in a single array (allTasks) and passed the array to Promise.all(allTasks) as input and waiting for resolve or reject.

If all the APIs run successfully then we are expecting the result in an array format (users response)

If any one of the APIs gets rejected then we should expect an error in a catch block.

Thank you guys for reading my little effort.

Please like and comment on the article if you really like it.