Youwang Deng

I'm a software developer, familiar with C#, Java, JavaScript, focus on full stack development.

Async Function in For Loop in JS

28 May 2019 » JavaScript, Async

In JavaScript, if a sequence of async methods has to been executed one by one, and the result should be returned after the last async method, then should use “for … of” syntax instead of “forEach”. Stackoverflow


Example that won’t work as Expected:

let items = [1,2,3];
let res = [];
items.forEach(async function(item)=> {
    let res1 = await asyncFunc1(item);
    let res2 = await asyncFunc2(res1);
    res.push(res2);
});
console.log(res);

Example that will work:

let items = [1,2,3];
let res = [];
for (const item of items) {
    let res1 = await asyncFunc1(item);
    let res2 = await asyncFunc2(res1);
    res.push(res2);
});
console.log(res);