Synchronous And Asynchronous Javascript – Simple Guide

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”. Meaning, 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 blocks of code run in parallel when it comes to asynchronous; Asynchronous functions run independently.

Yes, the whole idea of asynchronous Javascript is to prevent “blocking”, where a massive or lengthy piece of code stalls the rest of the processes. So just how do we do “asynchronous Javascript”? Let us explore all of those mysteries in this guide with some examples – Read on!

ⓘ 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.

 

 

REAL QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Synchronous Asynchronous
Useful Bits & Links The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example 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

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.

 

 

SYNCHRONOUS JAVASCRIPT

All right, let us now get started with the one you are already familiar with – Synchronous Javascript.

 

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 simple words, it 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 runs “by default”.

 

SIMPLE SYNCHRONOUS JAVASCRIPT EXAMPLE

1-sync.html
// (A) ADD FUNCTION
function add (first, second) {
  return first + second;
}
 
// (B) MULTIPLY FUNCTION
function multiply (first, second) {
  return first * second;
}
 
// (C) ADD, THEN MULTIPLY
// (C1) ADD(2, 3) WILL RUN FIRST
// (C2) FOLLOWED BY MULTIPLY(5, 5)
var result = multiply(add(2, 3), 5);
console.log(result); // 25

Yep. Pretty sure everyone already knows how this works –

  1. add(2, 3) will run first.
  2. Then followed by multiply(5, 5).
  3. Lastly, 25 will be assigned to result.

In other words, multiply() will wait for the output from add() before proceeding.

 

 

ASYNCHRONOUS JAVASCRIPT

Next, we break away from the tradition and go into asynchronous Javascript.

 

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.

 

ASYNC FUNCTIONS & PROMISES

2-async.js
// (A) ASYNCHRONOUS ADD
async function add (first, second) {
  return first + second;
}
 
// (B) RUN!
var result = add(2, 3);
console.log(result); // PROMISE

To define an asynchronous function, we simply add async in front. That’s all. But take note that async function will return a promise instead of the results directly. No need to be confused:

  • Remember that asynchronous functions run in parallel?
  • We don’t wait for it to finish running, and thus it returns a promise.
  • Simple English – “I promise to get back to you with the results”.

 

 

RESOLVING PROMISES

2-async.js
// (C) HERE'S HOW TO WORK WITH PROMISES
result
 
// (C1) RESOLVE RESULT
.then(res => {
  console.log(res); // 5
})

// (C2) OPTIONAL - CATCH ERROR
.catch(err => {
  console.error(err);
})

// (C3) OPTIONAL - FINALLY
.finally(() => {
  console.log("Finally");
});

So how do we “get” the results from asynchronous functions? Use a then-catch-finally block.

  • then Run this when the processing is complete.
  • catch Optional – Handle errors.
  • finally Optional – Run this regardless, error or not.

Yes, it works just like a try-catch-finally block.

 

ASYNC RUNS IN PARALLEL

3-async.js
// (A) ASYNC ADD & MULTIPLY
async function add (first, second) {
  return first + second;
}
async function multiply (first, second) {
  return first * second;
}
 
// (B) RUN!
add(2, 3).then(result => { console.log(result); }); // 5
multiply(5, 5).then(result => { console.log(result); }); // 25

What’s the big deal with asynchronous functions? Let us revisit the previous add() and multiply() example, but make them asynchronous. Yes, take extra note of how this one runs – add() and multiply() are calculating at the same time in parallel.

 

 

ASYNC CHAIN

4-chain.js
// (A) ASYNC ADD & MULTIPLY
async function add (first, second) {
  return first + second;
}
async function multiply (first, second) {
  return first * second;
}
 
// (B) RUN!
// (B1) EMPTY HOLDER
var result = null;
 
// (B2) ASYNC CHAIN
add(2, 3).then(res => {
  multiply(res, 5).then(res => {
    result = res;
    console.log(result); // 25
  });
});
 
// (C) NOTE - THIS WILL CONTINUE WHILE ADD-MULTIPLY CHAIN RUNS
console.log(result); // NULL OR 25

So far so good? Let us take that async magic to the next step. To do the previous “add then multiply”, we have to chain add.then(result => { multiply.then(result) => { ... } }). Yes, take extra note of how this runs again – The add-multiply asynchronous chain calculates independently. The rest of the script will continue to run.

 

AWAIT

5-await.html
// (A) ASYNC ADD & MULTIPLY
async function add (first, second) {
  return first + second;
}
async function multiply (first, second) {
  return first * second;
}

// (B) AWAIT
async function calc () {
  var result = await add(2, 3);
  console.log(result); // 5
  result = await multiply(result, 5);
  console.log(result); // 25
}
calc();

I know, having an insanely long .then chain can be pretty stupid. So here’s another mechanism the smart monkeys came up with – await. This should be self-explanatory, waits for the result from an asynchronous function. But please take note, await can only be used inside another async function.

 

 

OTHER ASYNCHRONOUS MECHANISMS – AJAX & WORKERS

Asynchronous functions are not the only “run in parallel” mechanisms in Javascript. Two other common ones are:

  • Asynchronous Javascript And XML (AJAX)
  • Web Workers – Threading.

I will leave some links below if you want to learn more.

 

USEFUL BITS & LINKS

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

 

INFOGRAPHIC CHEAT SHEET

Synchronous Asynchronous Javascript (Click to Enlarge)

 

LINKS & REFERENCES

 

THE END

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 *