高级前端js【Q245】有没有用过 Promise.allSettled() ,它是干什么的

有没有用过 Promise.allSettled() ,它是干什么的

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 247

Author 回答者: mrrs878

接收一个可迭代对象,其中每个成员都是Promise。在所有给定的Promise都已经fulfilledrejected后返回一个Promise,并带有一个对象数组,每个对象表示对应的Promise结果 相较于Promise.all,后者会在任何一个Promiserejected时立即结束 简单实现

const myPromiseSettled = (items) => {
  const onResolved = (value) => ({ status: "fulfilled", value });
  const onRejected = (reason) => ({ status: "rejected", reason });
  return Promise.all(
    items.map((item) => Promise.resolve(item).then(onResolved, onRejected)),
  );
};

Author 回答者: shfshanyue

@mrrs878 代码相当简洁了!

Author 回答者: justorez

function allSettled(promises = []) {
  return new Promise((resolve) => {
    let count = 0;
    let values = new Array(promises.length);
    const collect = (index, status) => (value) => {
      const prop = status === "fulfilled" ? "value" : "reason";
      values[index] = { status, [prop]: value };
      ++count === promises.length && resolve(values);
    };
    promises.forEach((promise, i) => {
      if (isPromise(promise)) {
        promise.then(collect(i, "fulfilled"), collect(i, "rejected"));
      } else {
        collect(i, "fulfilled")(promise);
      }
    });
  });
}