Deep PatelNavigate back to the homepage

Handling multiple API calls with Promise.allSettled()

Deep Patel
January 17th, 2021 · 1 min read

The Promise.allSettled() method returns a promise that resolves after all of the given promises have either fulfilled or rejected, with an array of objects that each describes the outcome of each promise.

1const promise1 = Promise.resolve(3);
2const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, 'foo'));
3const promises = [promise1, promise2];
4
5Promise.allSettled(promises).
6 then((results) => results.forEach((result) => console.log(result.status)));
7
8// expected output:
9// "fulfilled"
10// "rejected"

MDN doc


For example, look at the dummy data given below I, want to make an API call to get the client’s details by clientId

1[
2 {
3 bed : 'bed name',
4 clientId : '1548765'
5 },
6 {
7 bed : 'bed name2',
8 clientId : '1548766'
9 }
10]

For each client, I have to make an API call of getClientById and I don’t want my program to proceed further until details for all the clients is available

1// In this case what I can do is
2
3Promise.allSettled(
4 data.map(e=> {
5 return CALL_API(`client/${e.clientId}` , 'get')
6 })
7).then(responseArr => {
8 responseArr.forEach(res=>{
9 console.log(res);
10 // res.status & res.value
11 })
12})

More articles from Deep Patel

Create/ Publish your first NPM package

Create/ Publish your first NPM package.

June 14th, 2020 · 1 min read

How to Add Sentry to your Angular project with Graphql

How to Add Sentry to your Angular project with Graphql

February 6th, 2022 · 1 min read
© 2020–2022 Deep Patel
Link to $https://twitter.com/pateldeep_ethLink to $https://github.com/deep1144Link to $https://www.instagram.com/deep__1144/Link to $https://www.linkedin.com/in/patel-deep-dev/Link to $https://dribbble.com/Deep1144