2

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!

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You're right, the innercallback function is not passed by the async.each. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.