Can I use a async function as a callback in node.j

2019-08-28 08:05发布

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条回答
对你真心纯属浪费
2楼-- · 2019-08-28 08:57

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.

查看更多
登录 后发表回答