How to async loop an interable in JavaScript/NodeJS?

How to async loop an interable in JavaScript/NodeJS?

JavaScript uses an event loop, an endless loop whereby the engine waits for tasks, executes them and wait for callbacks. In NodeJS, even though it's single-threaded, with this manoeuvre, you can perform non-blocking I/O operations.

The one problem that arrises from this mechanism though, is that codes are not ran synchronously - that is - it does not follow procedures sequentially; rather, it continues with the call without waiting for return values.

Use Case - Iterating through Items

Assume a scenario where you need to get a list of products containing around 200 items from the database.

The aim is to map through each item and calculate the tax amount. If you simply go through each iteration, JavaScript event loop will continue proceeding and you will not have the expected result.

There are numerous solutions to approach this situation - including using the Async Library. After researching and experimenting with many approaches throughout the years, I stumbled upon a colleague's code using the following strategy:

In this loop, all the values in the list of products will be iterated. You don't need to use Promises.all or callbacks.

In other Programming Languages such as Ruby or Python, you can process the code synchronously without caring for Event Loops.

This is documented in the official MDN site: