admin管理员组

文章数量:1364018

I am currently using Promise.allSettled to wait for all my promises to finish(irrespective of whether they resolve or get rejected).

Since my project is pliant to Node v12.3.1 I am unable to use this? 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.
Adding shims is also not an option.

I am currently using Promise.allSettled to wait for all my promises to finish(irrespective of whether they resolve or get rejected).

Since my project is pliant to Node v12.3.1 I am unable to use this? 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.
Adding shims is also not an option.

Share Improve this question asked Mar 17, 2021 at 12:16 YetAnotherBotYetAnotherBot 2,1063 gold badges28 silver badges37 bronze badges 4
  • 3 "Adding shims is also not an option." then what solutions do you expect? All of them would basically be a variation of "make your own allSettled" – VLAZ Commented Mar 17, 2021 at 12:19
  • By adding shims I meant, not allowed to make changes to package.json. I am open to small snippets that I can add. – YetAnotherBot Commented Mar 17, 2021 at 12:21
  • Bit new to nodejs so please bare with me. – YetAnotherBot Commented Mar 17, 2021 at 12:21
  • 1 Pick a well known and used and tested polyfill and copy/paste the code, then? All the packages you'd be adding are going to be open source anyway. You can visit their GitHub and just see what the code is. – VLAZ Commented Mar 17, 2021 at 12:26
Add a ment  | 

3 Answers 3

Reset to default 12

There's a small polyfill trick that you can do manually to simulate the effects of Promise.allSettled.

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.

An alternative, if you do not want the object-like nature of Promise.all, the following snippet may help. This is very simple, you just need to add .catch method here.

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.

Library: https://www.npmjs./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.

本文标签: javascriptAlternative for PromiseallSettledStack Overflow