Synchronous & Asynchronous Javascript – A Simple Explanation

INTRODUCTION

CLASHING JAVASCRIPT?

Welcome to a beginner’s tutorial on synchronous and asynchronous Javascript. I am sure that at a certain point in the Javascript journey, code ninjas are eventually going to run into the topic of synchronous and asynchronous. Just what does that mean? What is the difference? Long story short:

  • Javascript is synchronous “by default”. The next line of code cannot run until the current one has finished, the next function cannot run until the current one has completed.
  • But when it comes to asynchronous, blocks of code run in parallel. The idea of asynchronous Javascript is to prevent “blocking”, where a massive or lengthy piece of code stalls the rest of the important processes.

So just how do we do “asynchronous Javascript”? Let us explore all of those mysteries in this guide with some examples – Read on to find out!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

 

PREAMBLE

DOWNLOAD & NOTES

First, here is the download link to the example source code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

There is nothing to install, just download and unzip into a folder. If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

SECTION A

THE BASICS

All right, let us now get started with a “boring section” on the raw basics of synchronous and asynchronous.

 

WHAT IS SYNCHRONOUS?

In program-to-program communication, synchronous communication requires that each end of an exchange of communication respond in turn without initiating a new communication.

WhatIs.com

This may seem a little difficult to understand at first, but let us zoom into the important part, which is “each end of an exchange of communication responds in turn without initiating a new communication”.

In the layman words, that simply means “synchronous functions will only run after the current one has completed”, or “synchronous functions will wait for the output from another before proceeding” – That is literally how Javascript usually runs “by default”.

 

 

SIMPLE SYNCHRONOUS JAVASCRIPT EXAMPLE

Still confused? Let us go through a simple example to illustrate that:

1a-sync-eg.js
function add (first, second) {
  return first + second;
}
function multiply (first, second) {
  return first * second;
}
var xyz = multiply (add(2, 3), 5); 
console.log(xyz); // 25

Yep. Pretty sure everyone already knows how this works – add() will run first, then followed by multiply(). In other words, multiply() will wait for the output from add() before proceeding.

 

WHAT IS ASYNCHRONOUS?

In computer programs, asynchronous operation means that a process operates independently of other processes.

WhatIs.com

This one should be self-explanatory too. Asynchronous is the “opposite” of synchronous. Functions and processes will run independently and parallel to each other – They don’t wait nor depend on each other.

 

 

SIMPLE ASYNCHRONOUS JAVASCRIPT EXAMPLE

1b-async-eg.js
async function add (first, second) {
  return first + second;
}
async function multiply (first, second) {
  return first * second;
}
add(2, 3).then(result => { console.log(result); }); // 5
multiply(5, 10).then(result => { console.log(result); }); // 50

To some beginners, this example may seem like add() runs first, then followed by multiply() – But the truth is that async function will not wait for each other. Both add() and multiply() actually run in parallel, independently from each other.

 

SO WHY ASYNCHRONOUS?

Javascript worked just fine as a synchronous language for donkey years, so the million-dollar question is – Why did the developers suddenly come up with all of these asynchronous gimmicks?

  • As in the introduction, a massive piece of code will stall the rest of the operations – We call this “blocking”.
  • With asynchronous scripts, we can let different processes run in parallel.
  • This results in better performance and user experience – People no longer have to stare at a “now loading” screen for too long.

 

 

SECTION B

ASYNCHRONOUS EXAMPLES

So far so good? The above section should have pretty much explained the basics of synchronous and asynchronous Javascript. But just how can we “do asynchronous Javascript”? Let us walk through a few more examples in this section.

 

ASYNC FUNCTIONS

2a-async-demo.js
async function add (first, second) {
  return first + second;
}
 
var added = add(99, 101);
console.log(added); // promise

var result = add(45, 55);
console.log(result); // promise

To do asynchronous functions in Javascript, we simply prepend an async in front of the function declaration. But getting the results from an async function can be pretty tricky for beginners – We would normally expect a function to return whatever result that is processed, but an async function returns a promise instead.

 

WHAT THE HECK IS A PROMISE?

So… where are the results!? How do we get it? How to deal with this promise thing? Let us keep calm and walk through this gimmick:

2b-promise.js
async function add (first, second) {
  return first + second;
}

var added = add(99, 101);
added.then(
  function(result){
    console.log(result); // 200
  }
).catch(
  function(error){
    console.log(error); // If any errors
  }
);
  • Remember that the function is now asynchronous? That is, the function may take a long time to run in the background.
  • In this case, Javascript will not directly return the processed results, but a promise instead. I.E. “I promise to get back to you with the results”.
  • There are 3 states to the promise:
    • pending – Initialized, still processing.
    • fulfilled – Done successfully.
    • rejected – Failed.
  • So, somewhat like a try-catch block, we have to use a then-catch block to handle a promise.

 

 

AWAIT

2c-await.js
async function add (first, second) {
  return first + second;
}

async function calc () {
  var result = await add(45, 55);
  console.log(result); // 100
}

calc();

Lastly, there are times where we just have to wait for the results from an async function, in this case, we can use the await statement. But please take note – await can only be used inside another async function.

 

ASYNCHRONOUS JAVASCRIPT AND XML (AJAX)

3a-page.html
<script>
function ajaxLoad () {
  // APPEND FORM DATA
  var data = new FormData();
  data.append('hello', 'world');

  // AJAX INIT
  var xhr = new XMLHttpRequest();
  xhr.open('POST', "3b-dummy.txt", true);
  xhr.onload = function(){
    document.getElementById("container").innerHTML = this.response;
  };

  // SEND
  xhr.send(data);
}
</script>
 
<div id="container"></div>
<input type="button" value="Click to LOAD" onclick="ajaxLoad()"/>
3b-dummy.txt
This is loaded from another file.

AJAX is one of the earlier implementations of asynchronous mechanisms in Javascript. What the heck is it, what does it do? Simply think of how the traditional online shopping carts and forms work in general – Submit a form, server-side processing, reload the entire page.

AJAX takes that “submit form” and “reload page” pain away – It does the loading in the background instead, and we can use it to dynamically send/receive data. For example, the user can click on an item to “add to cart”, and click on “next product page” at the same time – Both of these processes can run in parallel in the background, without having the reload the entire page.

P.S. If you are interested to learn more about AJAX, I have left a link in the extras section below.

 

 

EXTRA

USEFUL BITS & LINKS

That’s all for this tutorial, and here is a small section on some extras and links that may be useful to you.

 

WEB WORKERS

// This will not run on file://
// Will only run on http://
if (window.Worker) {
  var workerA = new Worker('SCRIPT-A.js');
  var workerB = new Worker('SCRIPT-B.js');
}

Some of you code ninjas may have used other programming languages and heard of “threading”. Yes, we can do threading in Javascript, But no, it is not done with asynchronous functions but with workers… As this is another big can of worms, I shall just leave it here as a quick introduction. Follow up with the web worker tutorial link if you want.

 

LINKS & REFERENCES

 

INFOGRAPHIC

Synchronous Asynchronous Javascript (Click to Enlarge)

 

CLOSING

WHAT’S NEXT?

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *