admin管理员组

文章数量:1023204

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

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

本文标签: