Deep's Blog


Deep's Blog


Handling multiple API calls with Promise.allSettled()

Deep's photo
·Jan 23, 2021·

2 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.

const promise1 = Promise.resolve(3);
const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, 'foo'));
const promises = [promise1, promise2];

  then((results) => results.forEach((result) => console.log(result.status)));

// expected output:
// "fulfilled"
// "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

    bed : 'bed name',
    clientId : '1548765'
    bed : 'bed name2',
    clientId : '1548766'

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

// In this case what I can do is 

Promise.allSettled(> {
    return CALL_API(`client/${e.clientId}` , 'get')
).then(responseArr => {
    // res.status & res.value

Did you find this article valuable?

Support Deep by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
Share this