如何在Node.js中执行一组同步和异步函数

我有像 JSON 这样的配置,我们可以在其中定义任何 JavaScript 函数。现在我有执行函数,它将采用该函数数组并执行。我怎样才能做到这一点?

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

如您所见,一个函数同步,另一个函数为async& await。将所有功能定义为async&await似乎很糟糕(创建了很多新的承诺)+ 我也无法将所有功能定义为同步。

感谢您提前回答。

回答

您可以使用Promise.all()来解析一系列承诺。

承诺以外的值将按原样返回

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

async function execute() {
  return Promise.all(listOfFuncs.map(func => func()));
}

// execute() will return a Promise which resolves to an array
// containing all results in the same order as the functions.
execute().then(result => console.log(result));

// Logs: [45, 54] after 100ms

没有本地函数来解析包含 Promise 的对象,但是一些库实现了替代 Promise API,以便更容易地使用更复杂的模式(取消、比赛等)。最著名的是蓝鸟。

它实现了一个Promise.props几乎可以做你想做的方法: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);
});


以上是如何在Node.js中执行一组同步和异步函数的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>