DEV Community

Deep
Deep

Posted on

8 2

Handling multiple API calls with Promise.allSettled()

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];

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

// expected output:
// "fulfilled"
// "rejected"
Enter fullscreen mode Exit fullscreen mode

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'
  }
]
Enter fullscreen mode Exit fullscreen mode

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(
  data.map(e=> {
    return CALL_API(`client/${e.clientId}` , 'get')
  })
).then(responseArr => {
  responseArr.forEach(res=>{
    console.log(res);
    // res.status & res.value
  })
})
Enter fullscreen mode Exit fullscreen mode

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay