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

I can see some strange behavior when all requests in multiple JavaScript promises, collected by Promise

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745518611a4631152.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信