'Is there a way to get values of only resolved promises?
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?
Solution 1:[1]
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);
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | CertainPerformance |
