3

I'm calling multiple services which includes network calls and other asynchronous services in my JavaScript application.

At first I was invoking these promises one by one. In the long run it's getting hard to maintain since I'm invoking more services.

I read somewhere in the internet that we can use Promise.all() to group all promises and execute everything at a time.

The issue is, if any one of the promise is getting rejected all other promises are also getting rejected, this is not what I need.

I'm working in a status dashboard where I need to ping multiple services and show whether the service is up or not. By using Promise.all, it's not working in a way I wished.

Tried another method Promise.any(), but it just resolves when any one is resolved.

Took a look at MDN docs, there are many functions for promise it's overwhelming to me because I'm a beginner in JavaScript.

Currently I've created a very own service which takes care of calling all the promises and counts with the response. Is there any cleaner way to do it?

  • sound like you shouldn't put these promise together at first? why you can have one rejected and still process the data? – apple apple Mar 26 '22 at 03:52
  • You may "enqueue" your promises into an Asynchronous Queue ([AQ](https://github.com/kedicesur/AQ)) and then control whatever you want to do with them. Get the resolving ones one after the other or even race them by neglecting the rejected ones. Try. – Redu Apr 14 '22 at 20:47

1 Answers1

3

Use Promise.allSettled, then filter out those that weren't fulfilled.

Promise.allSettled([
  Promise.resolve(3),
  Promise.reject(4),
  Promise.resolve(5),
])
  .then((results) => {
    const allFulfilledValues = results
      .filter(r => r.status === 'fulfilled')
      .map(r => r.value);
    console.log(allFulfilledValues);
  });
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320