I want to create an array of async functions but I can't understand why it works with map but not with the for loop. Can someone explain the differences between for loop and map in this case?
async function sleep(ms) {
await new Promise((r) => setTimeout(r, ms));
}
async function logic(i) {
let time = i * 500;
await sleep(time);
console.log(`${i} finished after ${time}`);
return time;
}
function exampleConstructResultsViaMap(data) {
const tasks = data.map((date, i) => {
const task = async() => logic(i);
return task;
});
return tasks;
}
function exampleConstructResultsViaFor(data) {
const tasks = [];
let i = 0;
for (const date of data) {
const task = async() => logic(i);
tasks.push(task);
i++;
}
return tasks;
}
(async() => {
const data = ['a', 'b'];
const tasksMap = exampleConstructResultsViaMap(data);
const resultsMap = await Promise.all(tasksMap.map((p) => p()));
console.log(resultsMap); // [0, 500]
const tasksFor = exampleConstructResultsViaFor(data);
const resultsFor = await Promise.all(tasksFor.map((p) => p()));
console.log(resultsFor); // [1000, 1000]
})();