Here is how I understand things currently:
async/await in a for-loop should pause execution until the promise resolves, meaning that the next iteration of the loop won't occur until that line finishes.
Consider the following array:
const data = [];
for (let i = 0; i <= 100000; i++) {
data.push(i);
}
Method 1: Awaiting Promises in a for-loop
async function method1() {
const startTime = new Date();
console.log('start:', startTime);
for (const item in data) {
await new Promise(resolve => {
if (item % 3 === 0) {
resolve({});
} else {
resolve(item)
}
});
}
const endTime = new Date();
console.log('finish:', endTime);
console.log('total time:', endTime-startTime);
}
Because it requires sequential execution of promises to continue through the loop, I figured using Promise.all would be a performance enhancement that leverages asynchronous processing to a greater degree:
Method 2: Promise.all following a for-loop
async function method2() {
const promises = [];
const startTime = new Date();
console.log('start:', startTime);
for (const item in data) {
const promise = new Promise(resolve => {
if (item % 3 === 0) {
resolve({});
} else {
resolve(item)
}
});
promises.push(promise);
}
await Promise.all(promises);
const endTime = new Date();
console.log('finish:', endTime);
console.log('total time:', endTime-startTime);
}
My reasoning: the loop would continue to bang out new Promises while each previously created Promise attempts resolve. So in my head, method 1 = blocking... while method 2 = less blocking.
When I run these both on repl.it, I found that method method 1 is actually quicker, almost by a factor of 2. Can somebody explain why this is? Shouldn't it be the other way around?