Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute batch of promise with Promise.allSettled()

With node v10.15.1 I try to use Promise.allSettled() to executes batches of Promise but it throw me an error

TypeError: Promise.allSettled is not a function

Is Promise.all() returning a promise ?

The Main function below return an object. Other functions use some Promises to create its "sub-object".

Why I need "batch of promise" : To create a sub-object, all the required promises must be settled. But not all the sub-objects are needed in the "main object".

const path = require('path');
const os = require('os');
const si = require('systeminformation');

function getFoo() {
  // all these promises have to be settled to construct the sub-object
  return Promise.all([si.system(), si.chassis()]).then(([system, chassis]) => {
    return { /* hidden for brevity : use system and chassis to return a single object */ };
  })
  .catch(ex => { /* hidden for brevity */ });
}

function getBar() {
  // all these promises have to be settled to construct the sub-object
  return Promise.all([si.osInfo(), si.uuid()]).then(([osInfo, uuid]) => {
    return { /* hidden for brevity : use osInfo and uuid to return a single object */ };
  })
  .catch(ex => { /* hidden for brevity */ });
}

function getBaz() {
  // all these promises have to be settled to construct the sub-object
  return Promise.all([os.networkInterfaces(), si.networkInterfaceDefault()]).then(([interfaces, defaultInterface]) => {
    return { /* hidden for brevity : use interfaces and defaultInterface to return a single object */ };
  })
  .catch(ex => { /* hidden for brevity */ });
}

function Main() {
  // some of these promises can be rejected
  Promise.allSettled([ getFoo(), getBar(), getBaz() ])
    .then(([foo, bar, baz]) => {
      return { foo, bar, baz }
    })
    .catch(ex => { /* hidden for brevity */ });
}

Main();

One Example of expected object

{
  foo: {
    prop: 'example',
    someOtherProps: 'We are there!'
  },
  baz: {
    test: 50
  }
}
like image 324
Firlfire Avatar asked Aug 20 '19 14:08

Firlfire


People also ask

What is promise allSettled?

The Promise. allSettled() method takes an iterable of promises as input and returns a single Promise . This returned promise fulfills when all of the input's promises settle (including when an empty iterable is passed), with an array of objects that describe the outcome of each promise.

What does promise () method do?

The . promise() method returns a dynamically generated Promise that is resolved once all actions of a certain type bound to the collection, queued or not, have ended. By default, type is "fx" , which means the returned Promise is resolved when all animations of the selected elements have completed.

Does promise allSettled run in parallel?

allSettled(promises) is a helper function that runs promises in parallel and aggregates the settled statuses (either fulfilled or rejected) into a result array.

What is the difference between promise all and promise allSettled?

Promise.all() will reject immediately upon any of the input promises rejecting. In comparison, the promise returned by Promise.allSettled() will wait for all input promises to complete, regardless of whether or not one rejects.


2 Answers

Promise.allSettled is available in node version >= 12.9

like image 77
Arlen Anderson Avatar answered Oct 11 '22 02:10

Arlen Anderson


allSettled = function(promiseList) {
    let results = new Array(promiseList.length);

    return new Promise((ok, rej) => {

        let fillAndCheck = function(i) {
            return function(ret) {
                results[i] = ret;
                for(let j = 0; j < results.length; j++) {
                    if (results[j] == null) return;
                }
                ok(results);
            }
        };

        for(let i=0;i<promiseList.length;i++) {
            promiseList[i].then(fillAndCheck(i), fillAndCheck(i));
        }
    });
}
like image 40
AndrewStone Avatar answered Oct 11 '22 01:10

AndrewStone