gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 09:07:03 24 4
gpt4 key购买 nike

我有类似 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();

如您所见,一个函数同步,另一个函数作为 asyncawait。将所有功能定义为 asyncawait 似乎很糟糕(创建了很多新的 promise )+ 我也不能将所有功能都定义为同步。

提前感谢您的回答。

最佳答案

您可以使用 Promise.all() 来解析一组 promise。

promise 以外的值将按原样返回

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

没有本地函数来解析包含 promise 的对象。

然而,一些库实现了替代的 Promise API,以便更容易地使用更复杂的模式(取消、竞争……)。最著名的是 bluebird 。

它实现了一个 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);
});

关于javascript - 如何在 Node.js 中执行一组同步和异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65356124/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com