简体   繁体   中英

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(eg 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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM