我可以在anode.js中使用异步函数作为回调吗? [英] Can I use a async function as a callback in node.js?

查看:45
本文介绍了我可以在anode.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.allmap:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆