I have a question about async.each behavior. consider the code:
const examples = [1,2];
const asyncTask = (index) => {
return new Promise(resolve => {
setTimeout(() => {
console.log(`Inside setTimeout-${index}`);
resolve(true);
}, 1500)
});
}
function testingAsyncEach(callback){
async.each(examples, (example, innerCallback) => {
asyncTask(example).then(isDone => {
console.log(`isDone: ${isDone}`);
innerCallback(null);
});
}, err => {
console.log('done testingAsyncEach');
return callback()
})
}
testingAsyncEach(() => {console.log('final callback testingAsyncEach');})
a simple code using the "async" module in nodejs, using the array [1,2] and on each item in the array executing the function "asyncTask" which returns a new promise which gets resolve after a timeout of 1.5 seconds.
in this scenario the output of the program is:
Inside setTimeout-1
isDone: true
Inside setTimeout-2
isDone: true
done testingAsyncEach
final callback testingAsyncEach
but when I changed the "testingAsyncEach" function to use the "await" syntax:
function testingAsyncEach(callback){
async.each(examples, async (example, innerCallback) => {
const isDone = await asyncTask(example);
console.log(`isDone: ${isDone}`);
innerCallback(null);
}, err => {
console.log('done testingAsyncEach');
return callback()
})
}
the async.each is not waiting for the "asyncTask" to end. output:
Inside setTimeout-1
isDone: true
done testingAsyncEach
final callback testingAsyncEach
Inside setTimeout-2
isDone: true
Can you please help me understand why using the "await" instead of the "then" change the behavior? how can I still use the "await" syntax and get the proper output? Thanks!