我可以在anode.js中使用异步函数作为回调吗? [英] Can I use a async function as a callback in node.js?
问题描述
我可以使用异步函数作为回调吗?像这样:
Can I use an async function as a callback? Something like this:
await sequelize.transaction(async function (t1) {
_.each(data, async function (value) {
await DoWork(value);
});
});
//Only after every "DoWork" is done?
doMoreWork();
据我所知,不能保证调用回调的函数将等待,直到答应被解决,然后再继续.正确的?确保将要发生的唯一方法是读取回调传递给的函数的源代码(例如事务"的源代码)?无论调用函数是如何实现的,是否都存在重写我的示例以使其正常工作的好方法?
As far as I understand there is no guarantee that the function invoking the callback will wait until the promise is solved before continuing. Right? The only way to be sure what will happen is to read the source code of the function the callback is passed to(e.g. source code of 'transaction')? Is there a good way to rewrite my sample to work properly no matter how the calling function is implemented?
推荐答案
async
函数可以用作回调,但是仅当以某种方式使用返回值(保证)来帮助保持正确的控制流时.一个例子是数组map
回调.
async
function can be as a callback but only if returned value (a promise) is used in some way that helps to maintain correct control flow. An example is array map
callback.
这与> forEach
的问题.问题在于,transaction
使用来自async
回调(承诺)的值,但是却忽略了each
回调中的值.
This is the same case as this problem with forEach
. The problem is that transaction
uses a value from async
callback (a promise) but a value from each
callback is ignored.
与async
串联执行诺言的方法是for..of
或其他循环语句:
The recipe for executing promises in series with async
is for..of
or other loop statement:
await sequelize.transaction(async function (t1) {
for (const value of data)
await DoWork(value);
});
与async
并行执行承诺的方法是Promise.all
和map
:
The recipe for executing promises in parallel with async
is Promise.all
with map
:
await sequelize.transaction(async function (t1) {
await Promise.all(data.map(async (value) => {
await DoWork(value);
}));
});
async
函数仅供参考,因为代码无法从中受益.这些可能是返回诺言的常规函数.
async
functions are left for reference only because the code doesn't benefit from them; these could be regular functions that return promises.
这篇关于我可以在anode.js中使用异步函数作为回调吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!