简体   繁体   English

如果多个 javascript Promise 使用 Promise.allSettled() 解决,Catch() 不会处理对 Promise 的拒绝

[英]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.当多个 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() always resolves, even if some promises passed to it reject. Promise.allSettled()总是解决,即使传递给它的一些承诺拒绝。 It resolves with an array of outcomes for each promise.它解决了每个承诺的一系列结果。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled 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.您可以改用Promise.all() ,它会在所有通过的 Promise 解决时解决,或者在任何通过的 Promise 拒绝时拒绝。

The catch statement will be executed when the error occurs.发生错误时将执行 catch 语句。 As the Promise.allSettled() always resolves, you can manually throw an error ie由于 Promise.allSettled() 总是解决,您可以手动抛出错误,即

 if(posts.status === "rejected"){ throw new Error('a status was rejected'); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM