'Catch() is not handling rejection of promise in case multiple javascript Promises to settle with Promise.allSettled()
I can see a strange behaviour when all of the request is being failed for multiple javascript Promises to settle with Promise.allSettled, .catch is unable to handle rejection.
const API_URL = "https://jsonplaceholder.typicode.com/";
const spinner = document.getElementById("spinner");
const output = document.getElementById("output");
function queryApi(endpoint){
return fetch(API_URL + endpoint).then(response => {
return response.ok ? response.json() : Promise.reject("Unsuccessful response");
})
}
const promise = Promise.allSettled([
queryApi("_posts"),
queryApi("_comments"),
queryApi("_users")
]);
promise
.then(results => {
console.log(results);
const posts = results[0];
const comments = results[1];
const users = results[2];
const statistics = [];
if(posts.status === 'fulfilled'){
statistics.push(`${posts.value.length} posts`);
}
if(comments.status === 'fulfilled'){
statistics.push(`${comments.value.length} comments`);
}
if(users.status === 'fulfilled'){
statistics.push(`${users.value.length} users`);
}
output.innerText = statistics.join("\n");
})
.catch(error => {
console.warn(error);
output.innerText = ":(";
})
.finally(() => {
spinner.remove();
});
Solution 1:[1]
Promise.allSettled()
always resolves, even if some promises passed to it reject. It resolves with an array of outcomes for each promise.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled
You can use Promise.all()
instead, which will resolve when all passed promises resolve or reject when any passed promise rejects.
Solution 2:[2]
The catch statement will be executed when the error occurs. As the Promise.allSettled() always resolves, you can manually throw an error i.e.
if(posts.status === "rejected"){
throw new Error('a status was rejected');
}
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 | madzong |
Solution 2 | Uzair Saeed |