JavaScript loops — how to handle async/await

October 31, 2017 0 Comments

JavaScript loops — how to handle async/await

 

 

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):

Old-school loop

It is good, it is fast, but it has many readability and maintenance issues. Then I used to use its better version:

Ah. This version of loops is really nice.

JavaScript language is developing very fast. We have more features and new syntax. One of my favorite is async/await. I am using it more frequently now. And sometimes I have a situation where I need to do something with items in an array asynchronously.

How to use await inside a loop? Let’s just write async function and await each task.

Wrong example. It will throw an error.

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:

Done!
1
2
3

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:

Run async operation as sequence

This will give us expected output:

1
2
3
Done!

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.


Tag cloud