Promise.allSettled 的替代方案

Adi*_*pta 0 javascript node.js es6-promise

我目前正在Promise.allSettled等待我所有的承诺完成(无论它们是否解决或被拒绝)。

由于我的项目符合Node v12.3.1我无法使用这个?我还可以使用哪些其他简单的替代方案。

示例代码:

async function runner() {
    let promises = [];
    for(let i=0; i<10; i++) {
        promises.push(fetcher())
    }
    await Promise.allSettled(promises).then(([results]) => console.log(results.length));
    console.log('continue work...');
}
Run Code Online (Sandbox Code Playgroud)

注意:Promise.allSettled 可从 获得Node version >12.9
添加垫片也不是一种选择。

Nic*_*s D 11

您可以手动执行一个小的 Polyfill 技巧来模拟Promise.allSettled.

这是片段。

if (!Promise.allSettled) {
  Promise.allSettled = promises =>
    Promise.all(
      promises.map((promise, i) =>
        promise
          .then(value => ({
            status: "fulfilled",
            value,
          }))
          .catch(reason => ({
            status: "rejected",
            reason,
          }))
      )
    );
}

Promise.allSettled(promises).then(console.log);
Run Code Online (Sandbox Code Playgroud)

这意味着映射所有的承诺,然后返回结果,无论是成功还是拒绝。

另一种选择是,如果您不想要 的类似对象的性质Promise.all,以下代码片段可能会有所帮助。这个很简单,你只需要.catch在这里添加方法即可。

const promises = [
  fetch('/something'),
  fetch('/something'),
  fetch('/something'),
].map(p => p.catch(e => e)); // this will prevent the promise from breaking out, but there will be no 'result-object', unlike the first solution.

await Promise.all(promises);
Run Code Online (Sandbox Code Playgroud)

  • 我将 `.then(value =&gt; ({ status: "fulfilled", value, })).catch(reason =&gt; ({ status: "rejected", Reason, }))` 替换为 `.then(value =&gt; ({ 状态: "已完成", 值, }), 原因 =&gt; ({ 状态: "已拒绝", 原因, }))`。 (2认同)