Promise and Async/Await: Promise was introduced in modern Javascript, to deal with asynchronous operations. However, there are times when you want to wait for multiple promises to settle, whether they resolve or reject. This is where Promise.allSettled() comes into play.
Promise. allSettled() is a method that returns a promise that resolves once all the given promises have either resolved or rejected, with an array of objects that each describe the outcome of each promise. Unlike Promise.all(), which fails fast (rejecting as soon as one of the promises rejects), allSettled() will wait for all promises to complete and give you an array of results that includes both resolved values and rejection reasons.
You should use Promise. allSettled() when you want to wait for all of your promises to be completed, regardless of whether they resolved or rejected. This comes in handy in cases, where you only want to gracefully handle success and failure, without breaking at the first rejection.
Let’s say you are going to fetch data from multiple APIs in a dashboard application. While some of these APIs could be down, but you still want to take as much data as you can without crashing your application.
const fetchData = (url) => fetch(url).then(res => res.json());
const urls = ['https://api.example.com/data1', 'https://api.example.com/data2', 'https://api.example.com/data3'];
Promise.allSettled(urls.map(fetchData))
.then(results => {
results.forEach(result => {
if (result.status === 'fulfilled') {
console.log('Data:', result.value);
} else {
console.error('Error:', result.reason);
}
});
});
Using Promise.allSettled() allows you to handle the outcome of each promise individually. For better understanding, in this case, when one API fails, the other APIs data can still go on to be processed and the application can still run without breaking.
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our NodeJS Expertise.