[Fixed] Sequence of code execution in Node.js app

Issue

I have always wondered about this and have never found a convincing answer.

Please consider the following case:

var toAddress = '';
if(j==1)
{
  toAddress="[email protected]";
}
else
{
  toAddress="[email protected]";
}

sendAlertEmail(toAddress);

Can I be certain that by the time my sendAlertEmail() function is called, I will have ‘toAddress’ populated?

Solution

For code like the sample you provided:

var toAddress = '';
if(j==1)
{
  toAddress="[email protected]";
}
else
{
  toAddress="[email protected]";
}

sendAlertEmail(toAddress);

You can definitely be certain that it is strictly sequential. That is to say that the value of toAddress is either "[email protected]" or "[email protected]".

But, for code like the following:

var toAddress = '';
doSomething(function(){
  if(j==1)
  {
    toAddress="[email protected]";
  }
  else
  {
    toAddress="[email protected]";
  }
});

sendAlertEmail(toAddress);

Then it depends on whether the function doSomething is asynchronous or not. The best place to find out is the documentation. The second best is looking at the implementation.

If doSomething is not asynchronous then the code execution is basically sequential and you can definitely be certain that toAddress is properly populated.

However, if doSomething is asynchronous then you can generally be certain that the code execution is NOT sequential. Since that is one of the basic behavior of asynchronous functions – that they return immediately and execute the functions passed to them at a later time.

Not all functions that operate on functions are asynchronous. An example of synchronous function is the forEach method of arrays. But all asynchronous functions accept functions as arguments. That’s because it’s the only way to have some piece of code executed at the end of the asynchronous operation. So whenever you see functions taking functions as arguments you should check if it’s asynchronous or not.

Leave a Reply

(*) Required, Your email will not be published