简体   繁体   English

Promise.allSettled 的替代品

[英]Alternative for Promise.allSettled

I am currently using Promise.allSettled to wait for all my promises to finish(irrespective of whether they resolve or get rejected).我目前正在使用Promise.allSettled等待我的所有承诺完成(无论它们是解决还是被拒绝)。

Since my project is compliant to Node v12.3.1 I am unable to use this?由于我的项目符合Node v12.3.1我无法使用它吗? What other simple alternatives can I use.我还可以使用哪些其他简单的替代方案。

Sample code:示例代码:

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

Note : Promise.allSettled is available from Node version >12.9 .注意: Promise.allSettled 可从Node version >12.9获得。
Adding shims is also not an option.添加垫片也不是一种选择。

There's a small polyfill trick that you can do manually to simulate the effects of Promise.all .您可以手动执行一个小的 polyfill 技巧来模拟Promise.all的效果。

Here's the snippet.这是片段。

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

That means map all of the promises, then return the results, either successful or rejected.这意味着 map 所有的承诺,然后返回结果,成功或拒绝。

An alternative, if you do not want the object-like nature of Promise.all , the following snippet may help.另一种选择是,如果您不希望Promise.all具有类似对象的性质,则以下代码段可能会有所帮助。 This is very simple, you just need to add .catch method here.这很简单,你只需要在这里添加.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);

Returns a promise that is resolved after all the promises given have been fulfilled or rejected, with a series of objects that describe the result of each promise.返回一个 promise,它在所有给定的承诺都被履行或拒绝后被解决,并带有一系列对象,描述每个 promise 的结果。

Library: https://www.npmjs.com/package/promise-ax库: https://www.npmjs.com/package/promise-ax

Example:例子:

const { createPromise } = require('promise-ax');
const promiseAx = createPromise();
const promise1 = Promise.resolve(4);
const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, new Error("error")));
const promise3 = Promise.reject("error");
const promise4 = promiseAx.resolve(8);
const promise5 = promiseAx.reject("errorAx");
const asyncOperation = (time) => {
    return new Promise((resolve, reject) => {
        if (time < 0) {
            reject("reject");
        }
        setTimeout(() => {
            resolve(time);
        }, time);
    });
};
const promisesToMake = [promise1, promise2, promise3, promise4, promise5, asyncOperation(100)];
promiseAx.allSettled(promisesToMake).then((results) =>   results.forEach((result) => console.log(result)));
// Salida esperada:
// 4
// Error: error
// error
// 8
// errorAx
// 100

You can try something like this:你可以尝试这样的事情:

await (Promise as any).allSettled(promises).then(console.log);

This works in typescript.这适用于 typescript。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM