Exploring Basic Asynchronous Javascript

Published May 03, 2017Last updated May 09, 2017

Trying to wrap your head around asynchronous javascript, here’s a post to help.

For asynchronous javascript, the code sequence is not sequential which means the code is not necessarily executed one after the other. In most cases, a program will be executed out of the order in which the code is written. Therefore, you can’t count on one thing to happen before the next occurs.
Here’s a example of a synchronous javascript function, in which case we can predict in what order the statements will be logged:

//Example 1
function one(){
function two(){
function three(){
Output Expected:

That was quite easy to follow, so let’s transition to an asynchronous javascript example and explore what we can learn.

//Example 2: 
function runNumbers(){
  setTimeout(one, 0); 
  setTimeout(three, 0);
  setTimeout(two, 0); 
  console.log("We previously counted up to 3!"); 
Output Expected:
We previously counted up to 3!

Above is an example of code not executed in a sequential order. Let’s dissect what is going on in the code snippet (Example 2) above. The function runNumbers calls on the predefined functions, one, two, three with the setTimeout() function.

The setTimeout() places the functions in the order they are called in a queue and the queue is only executed only when there is nothing left to do. Therefore, our console.log() statements within the functions are executed first before the functions in the queue. Hence, the output in the order above.

Fun fact : If something exists within a queue, you can not return it or error handle it.

The common techniques of asynchronous programming in Javascript are callback functions and promise objects. Both of which will be explored in my next post.
Thanks for reading.


Andrew Hart : Understanding Asynchronous Javascript

Discover and read more posts from Shalom Ayidu
get started