Can I use a async function as a callback in node.js?

ぃ、小莉子 提交于 2019-12-25 03:35:31

问题


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?


回答1:


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.

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.

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

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 functions are left for reference only because the code doesn't benefit from them; these could be regular functions that return promises.



来源:https://stackoverflow.com/questions/53154982/can-i-use-a-async-function-as-a-callback-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!