One of the core principles in NodeJS is the non-blocking design or asynchronous API or Event Loop architecture. There is a lot of noise made about this principle in the internet. A beginner who sets out to learn what this means is bound to get a bit confused. Let me see if I can add a little bit to that confusion :).
Let’s take a look at this code.
var numbers = [1,2,3,4,5,6]; numbers.forEach(function(num){ console.log(num); });
We print each number in the array using the forEach function. Usually developers mistake this to be asynchronous API. This code is completely synchronous, it’s functional style of coding. If you have 100 numbers and execute this code, it will get executed synchronously blocking everything else(???). So what is asynchronous then?
Let’s take a look at the following code that prints all the numbers in the collection.
var numbers = [1,2,3,4,5,6]; numbers.forEach(function(num){ setTimeout(function(){ console.log(num); },0); });
If you try to understand this code with naked eye, we’ll conclude that there’s no difference with the previous version. The setTimeout() function gets executed after 0 milliseconds. So, we get the same output. Ahem!
It’s only partially correct. A call to setTimeout() function involves an asynchronous call to the actual implementation of setTimeout(). The callback function is queued and executed later. In other words, this is an example of asynchronous API.
Now, if you’re wondering what the hell is going on, I am going to ask you to take a look at a fantastic tool called Loupe. Copy paste the both the versions of the code separately, and see the magic that happens before your eyes. See for yourself what Event Loop is.