I have a for loop in which there is a function call and that function further has some async code. Now the issue is that the for loop doesn't wait for the async code to return from the nested function call and continues iterating.
The function aFunctionThatRunsAsync
comes from a library that I have no control over.
Below is all the code.
// arr.length = 2
for (let i in arr) {
console.log(i, 'i1')
functionOne(arr[i], i, (err, res) => {
console.log(res)
})
}
function functionOne(inp, idx, callback) {
console.log(idx, 'i1')
const processor = aFunctionThatRunsAsync(inp, err => {
if (err) return callback(err);
});
processor.on('complete', data => {
console.log(data, idx, 'i3')
return callback(null, data)
});
}
Problem:
The log looks like this after the execution of the code:
0 i1 // expected
0 i2 // expected
1 i1 // unexpected, expected to have logged: data(obj) i3
1 i2 // unexpected, expected to have logged: 1 i1
And finally logs:
data(obj) 0 i3
data(obj) 1 i3 // Not always in the same order
I want the for loop to wait for the async code to return/log and run synchronously in the correct order so the final output look like this:
0 i1
0 i2
data(obj) 0 i3
1 i1
1 i2
data(obj) 1 i3