How to run async loops in sequence or in parallel?
Before doing asynchronous magic with loops I want to remind you how we write classical synchronous loops.
Long time ago I was writing loops like this (probably you too):
It is good, it is fast, but it has many readability and maintenance issues. Then I used to use its better version:
How to use await inside a loop? Let’s just write async function and await each task.
This code will throw a syntax error. Why? Because we can not use await inside synchronous function. As you can see “processArray” is async function. But anonymous function that we use for forEach is synchronous.
How to fix previous issue? We can define anonymous function as asynchronous as well:
But forEach will not wait until all items are finished. It will just run tasks and go next. As a proof let’s write simple test:
The output will be:
It can be ok if you don’t need to wait the results. But in almost all cases this is not a good logic.
To wait the result we should return back to old-school “for loop”, but this time we can use modern version with for..of construction (thanks to Iteration Protocol) for better readability:
This will give us expected output:
The code will handle each item one by one in series. But we can run it in parallel!
We can slightly change the code to run async operations in parallel:
This code will run many “delayLog” tasks in parallel. But be carefull with very large array (too many tasks in parallel can be too heavy for CPU or memory).
That is all. Thanks for reading!
Do you have performance issues with your web-app? I can help you.