Home > Web Front-end > JS Tutorial > How Can I Wait for All Promises to Settle, Even if Some Fail?

How Can I Wait for All Promises to Settle, Even if Some Fail?

Mary-Kate Olsen
Release: 2025-01-03 11:08:39
Original
179 people have browsed it

How Can I Wait for All Promises to Settle, Even if Some Fail?

Waiting for All Promises, Regardless of Failure

In scenarios where you have a series of promises making network requests that may encounter failures, you might prefer to wait for all promises to complete before proceeding, even if some fail.

The built-in Promise.allSettled method provides a straightforward solution:

Promise.allSettled([promise]).then(([result]) => {
  // Reached regardless of outcome
  // {status: "fulfilled", value: 33}
});
Copy after login

Prior to the introduction of Promise.allSettled, you could use a reflect function to achieve the same result:

const reflect = (p) => p.then(
  (v) => ({ v, status: "fulfilled" }),
  (e) => ({ e, status: "rejected" })
);

reflect(promise).then((v) => {
  console.log(v.status);
});
Copy after login

Alternatively, extending the reflect function to work with an array of promises:

function reflect(promises) {
  return Promise.all(promises.map((p) => {
    return p.then((v) => ({ v: v, status: "fulfilled" }),
                   (e) => ({ e: e, status: "rejected" }));
  }));
}

reflect(promises).then((results) => {
  var success = results.filter((x) => x.status === "fulfilled");
});
Copy after login

By utilizing these techniques, you can gracefully handle network failures and ensure that your code continues to execute as intended, regardless of whether some promises are successful or not.

The above is the detailed content of How Can I Wait for All Promises to Settle, Even if Some Fail?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template