How to use JavaScript Promise.all with realtime code example [Axios GET Calls]
Tags: javascript, beginners, webdev, react
Published: 2022-08-06 08:53:00

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

The basic syntax of Promise.all is

```
  Promise.all([promise1, promise2,.....])
   .then(result=>{
     //Congrats! Promise got resolved.
    }).catch(err=>{
     //Ohh ! Promise got rejected.
    })
```
where promise1, promise2 are async functions which also returns promise.

## When to use Promise.all method
When you have group of asynchronous task to process in 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);
    })
```

Result 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 function so each function will resolved respectively after 1,2 and 3 seconds but Promise.all will resolved 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 resolved 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 result in then-able.
Otherwise if any one of the Promise function get 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 catch block 

```
Error: p3 rejected
```

## Now Lets see the realtime example of Promise.all().

Suppose you have dashboard where you have to call 3 APIs
Till the time api is calling you have to show loader on the screen. So you can achieve this very easily by using Promise.all() method. 
Please refer 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 loader over here
    }).catch((err)=>{
        //If error comes then also you have to stop 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 calls 3 api for UserID 1,2 and 3 so for that we have grouped 3 apis call in a single array (allTasks) and passing the array to Promise.all(allTasks) as an input and waiting for resolve or reject.

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

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

Thank you guys for reading my little effort.

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