当多个 JavaScript Promise 中的所有请求(由
Promise.allSettled
收集)失败时,我可以看到一些奇怪的行为:.catch()
不处理拒绝。
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();
});
Promise.allSettled()
总是能够解决,即使传递给它的一些承诺被拒绝。每个承诺都会产生一系列结果。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled
您可以使用
Promise.all()
来代替,当所有通过的 Promise 解决时,它将解决;当任何通过的 Promise 拒绝时,它将被拒绝。
发生错误时将执行catch语句。由于 Promise.allSettled() 始终会解析,因此您可以手动抛出错误,即
if(posts.status === "rejected"){
throw new Error('a status was rejected');
}