Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a array of synchronous and asynchronous functions in Node.js

I have config like JSON where we can define any JavaScript functions inside. Now I have execution function which would take that array of functions and execute. How can I do that?

const listOfFuncs = [
  {
    "func1": (...args) => console.log(...args)
  },
  {
    "func2": async (...args) => {
      return await fetch('some_url');
    }
  }
]

function execute() {
  // how to execute the above array of functions now ?
}

// Should this be called as await execute()? 
execute();

As you can see one function sync & another function as async & await. Defining everything function as async & await seems bad ( creating a lot of new promises ) + I can't define all function as synchronous also.

Thanks for your answer in advance.

like image 226
Sathish Avatar asked Oct 23 '25 09:10

Sathish


1 Answers

You can use Promise.all() to resolve an array of promises.

Values other than promises will be returned as-is

const listOfFuncs = [
  () => 45,
  async () => new Promise(resolve => {
      setTimeout(() => resolve(54), 100);
  }),
  () => Promise.resolve(34)
];

// Convert to list of promises and values
const listOfMixedPromisesAndValues = listOfFuncs.map(func => func());

// Promise.all returns a Promise which resolves to an array
// containing all results in the same order.
Promise.all(listOfMixedPromisesAndValues).then(result => {
  // Logs: [45, 54, 34] after 100ms
  console.log(result)
});

There is no native function to resolve an object containing promises.

However some libraries implement alternative Promise API, to make it easier to use more complex pattern (cancellation, races, ...). The most well known is Bluebird.

It implements a Promise.props methods which almost do what you want: http://bluebirdjs.com/docs/api/promise.props.html

var Promise = require("bluebird");

Promise.props({
    pictures: getPictures(),
    comments: getComments(),
    tweets: getTweets()
}).then(function(result) {
    console.log(result.tweets, result.pictures, result.comments);
});
like image 175
Eloims Avatar answered Oct 25 '25 00:10

Eloims