DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for How to use JavaScript Promise.all with realtime code example [Axios GET Calls]
Imran shaikh
Imran shaikh

Posted on

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

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.
    })
Enter fullscreen mode Exit fullscreen mode

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);
    })
Enter fullscreen mode Exit fullscreen mode

Result returned from the above code snippet

[ 'p1 completed', 'p2 completed', 'p3 completed' ]
Enter fullscreen mode Exit fullscreen mode

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);
    })

Enter fullscreen mode Exit fullscreen mode

This code snipped will be coming in catch block

Error: p3 rejected
Enter fullscreen mode Exit fullscreen mode

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);
    })
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (2)

Collapse
 
lukeshiru profile image
Luke Shiru

A few things:

  • I know is an example for Promise.all, but ideally you should just fetch the list instead of doing 3 requests to the back-end. Is bad for the client and for the API itself. So if at work somebody ask you to do this, you should push back on it and ask the API folks to do a proper endpoint to fetch a subset of the users.
  • For this kind of tasks, Promise.allSetled might be way better than Promise.all.
  • You really don't need axios for this.
  • You might want to use ESM import instead of CJS require.

The code with the minimum fixes keeping the multiple requests:

const getUser = id =>
    fetch(`https://reqres.in/api/users/${id}`).then(response =>
        response.json(),
    );

const getUsers = ids => Promise.allSettled(ids.map(getUser));

getUsers([1, 2, 3]).then(console.log).catch(console.error);
Enter fullscreen mode Exit fullscreen mode

The code using a single end-point (which is what you should do):

const getUsers = params =>
    fetch(`https://reqres.in/api/users?${new URLSearchParams(params)}`).then(
        response => response.json(),
    );

getUsers({ per_page: 3 })
    .then(({ data }) => console.log(data))
    .catch(console.error);
Enter fullscreen mode Exit fullscreen mode

Cheers!

Collapse
 
jaymajors profile image
Jason Major

Really enjoyed the article thanks for sharing.

🌚 Life is too short to browse without dark mode