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
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 arraymap
callback.This is the same case as this problem with
forEach
. The problem is thattransaction
uses a value fromasync
callback (a promise) but a value fromeach
callback is ignored.The recipe for executing promises in series with
async
isfor..of
or other loop statement:The recipe for executing promises in parallel with
async
isPromise.all
withmap
:async
functions are left for reference only because the code doesn't benefit from them; these could be regular functions that return promises.