简体   繁体   中英

nodejs - async.each function with async operation on each iteration

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!

According to the documentation of the async module, if you pass an async function, it won't pass the innerCallback to your function. I believe that your innerCallback(null) call therefore errored, making the async.each return early. (the 2nd example is already "launched" though, so that still happens afterwards)

Check if err is set to an error, and if so, log it.

Should that be the issue, removing the innerCallback argument and call should solve it.

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