最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Catch() is not handling rejection of promise in case multiple javascript Promises to settle with Promise.allSettled() - Stack Ov

programmeradmin1浏览0评论

I can see some strange behavior when all requests in multiple JavaScript promises, collected by Promise.allSettled, fail: .catch() doesn't handle the rejections.

const API_URL = "/";

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("_ments"),
    queryApi("_users"),
]);

promise
    .then((results) => {
        console.log(results);
        const posts = results[0];
        const ments = results[1];
        const users = results[2];
        const statistics = [];
        if (posts.status === "fulfilled") {
            statistics.push(`${posts.value.length} posts`);
        }
        if (ments.status === "fulfilled") {
            statistics.push(`${ments.value.length} ments`);
        }
        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();
    });

I can see some strange behavior when all requests in multiple JavaScript promises, collected by Promise.allSettled, fail: .catch() doesn't handle the rejections.

const API_URL = "https://jsonplaceholder.typicode./";

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("_ments"),
    queryApi("_users"),
]);

promise
    .then((results) => {
        console.log(results);
        const posts = results[0];
        const ments = results[1];
        const users = results[2];
        const statistics = [];
        if (posts.status === "fulfilled") {
            statistics.push(`${posts.value.length} posts`);
        }
        if (ments.status === "fulfilled") {
            statistics.push(`${ments.value.length} ments`);
        }
        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();
    });

Share Improve this question edited May 6, 2024 at 11:13 Ripeadori 53 bronze badges asked May 1, 2022 at 7:17 Kunal RanjanKunal Ranjan 1951 gold badge3 silver badges13 bronze badges 1
  • Please use Observables. They will help you write your code reactively and handle APIs in optimal way. Also instead of fetch you can use HttpClient. Try and utilize Angular framework's features and you'll see improvements in both application as well as developer experience. – Aakash Goplani Commented May 1, 2022 at 7:28
Add a ment  | 

2 Answers 2

Reset to default 4

Promise.allSettled() always resolves, even if some promises passed to it reject. It resolves with an array of outes for each promise.

https://developer.mozilla/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.

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'); 
}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论