Codementor Events

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(){
  console.log("One"); 
}
function two(){
  console.log("Two"); 
}
function three(){
  console.log("Three"); 
}
Output Expected:
One 
Two
Three

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!"); 
  console.log("Four");
}
Output Expected:
We previously counted up to 3!
**Four**
**One**
**Three**
**Two**

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.

References:

Andrew Hart : Understanding Asynchronous Javascript
https://www.youtube.com/watch?v=vMfg0xGjcOI

Discover and read more posts from Shalom Ayidu
get started
post commentsBe the first to share your opinion
Show more replies