How to handle asynchronous For loop in JavaScript


Since JavaScript is a single-threaded programming environment, some times it gives confusing outputs when time-consuming processes are executed middle of a code block. Using Asynchronous JavaScript such as async, await and promises developers can overcome the occurrence of those confusing outputs.

From today’s article, I am going to talk about how an asynchronous for loop can be handle in JavaScript.


Before moving further it would be better to have mentioned that I am not going to explain basic concepts of async, await and promises in JavaScript. I am going to explain only about handling asynchronous for loop.


Example time-consuming function

I have created a time-consuming function to show how it works with different for loops.

1
2
3
4
5
6
7
const waitFunc = () => {
return new Promise(res => setTimeout(res, 5000));
}
const asyncDemoFunction = async (str) => {
await waitFunc();
console.log(str);
}

Is forEach() wait for results?

Test using an asynchronous function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var demoList = ['a','b','c'];
const waitFunc = () => {
return new Promise(res => setTimeout(res, 5000));
}
const asyncDemoFunction = async (str) => {
await waitFunc();
console.log(str);
}
//forEach example
const forEachWithAsync = (demolst) => {
demolst.forEach(async (i) =>{
await asyncDemoFunction(i);
});
console.log("done");
}
forEachWithAsync(demoList);

results:

1
2
3
4
done
a
b
c

Async for loop without wait

From this example, we can clearly see forEach(), not giving the expected results and not waiting until the finishing of execution of the time-consuming function.

Q: How to write For Loop to wait for results?

a: using thefor loop in an asynchronous function. 😀

let’s see an example of how to do it

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var demoList = ['a','b','c'];
const waitFunc = () => {
return new Promise(res => setTimeout(res, 5000));
}
const asyncDemoFunction = async (str) => {
await waitFunc();
console.log(str);
}
//for loop example
const asyncForLoop = async (strList) => {
for (const str of strList) {
await asyncDemoFunction(str);
}
console.log("done");
}
asyncForLoop(demoList);

result:

1
2
3
4
a
b
c
done

Async for loop with wait

for loop gave the expected answer and waited until the finishing of execution of the time-consuming function.

Don’t hesitate to share any comment with me.