Synchronous VS Asynchronous Javascript (Simple Examples)

Welcome to a tutorial on synchronous and asynchronous Javascript. Dear code ninja, so you have finally stumbled on the topic of synchronous and asynchronous. Just what does that mean? What is the difference? Why is it important? 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 been completed.
  • But when it comes to asynchronous, blocks of code run in parallel, and functions are processed independently.

That covers the quick basics, but read on if you need actual examples!

 

 

TLDR – QUICK SLIDES

[web_stories_embed url=”https://code-boxx.com/web-stories/sync-async-javascript/” title=”Synchronous And Asynchronous Javascript” poster=”https://code-boxx.com/wp-content/uploads/2021/11/STORY-JS-20230518.webp” width=”360″ height=”600″ align=”center”]

Fullscreen Mode – Click Here

 

TABLE OF CONTENTS

 

 

SYNCHRONOUS JAVASCRIPT

All right, let us now get started with synchronous Javascript – Which you should already be familiar with.

 

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
var result = multiply(add(2, 3), 5);
console.log(result); // 25

Wait, isn’t this the “usual way” to define functions? Isn’t this “normal Javascript”? Yes, remember “Javascript is synchronous by default” in the introduction snippet? So in this example:

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

In other words:

  • multiply() will wait for the output from add() before proceeding.
  • var result will only be assigned when all the calculations are complete.

That is synchronous in a nutshell – One process will wait for another to complete before proceeding.

 

 

ASYNCHRONOUS JAVASCRIPT

So far so good? Let us now break away from the tradition, and enter the world of asynchronous Javascript.

 

ASYNC FUNCTIONS & PROMISES

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

To define an asynchronous function, we just prepend async in front of the function(). That’s all, add() will now run independently when called. Sounds stupidly simple enough? But the next part will definitely trip a lot of people.

  • In synchronous Javascript, add(2, 3) will wait for the processing to complete and returns 5.
  • But in asynchronous Javascript, it returns a PROMISE instead.
  • What in the world is a PROMISE? Remember that “functions run independently” in asynchronous Javascript? Yes, we don’t wait for the function to finish processing.
  • A PROMISE essentially mean “the function is now running (not sure how long it will take), I promise to get back to you with the results when it is done processing”.

 

 

RESOLVING PROMISES

2b-resolve-promise.html
// (A) ASYNC ADD
async function add (first, second) {
  return first + second;
}
 
// (B) RUN ASYNC FUNCTION
add(2, 3)
 
// (C) THEN RESOLVE RESULT ON COMPLETE
.then(result => {
  console.log(result);
  // DO SOMETHING
})
 
// (D) OPTIONAL - CATCH ERRORS
.catch(err => console.log(error))
 
// (E) OPTIONAL - FINALLY
.finally(() => console.log("Finally"));

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

  • then() This will be triggered when the processing is complete.
  • catch() Optional. Handle errors.
  • finally() Optional. This will run at the end, regardless of success or error.

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

 

 

ASYNC CHAIN

Now that you have a basic understanding of async function(), let us do a small experiment and try to run the asynchronous functions as if they were synchronous.

2c-async-chain.html
// (A) ASYNC ADD & MULTIPLY
async function add (first, second) {
  return first + second;
}
 
// (B) MULTIPLY FUNCTION
async function multiply (first, second) {
  return first * second;
}
 
// (X) BAD!
var result = multiply(add(2, 3), 5);
console.log(result); // PROMISE - NAN

The result, a PROMISE that will resolve to “not a number” NaN. Why is that so?

  • Calling add() and multiply() will immediately return a PROMISE. We don’t wait for asynchronous functions to finish, remember?
  • So simply, multiply(PROMISE, 5) results in NaN.

To “properly chain” asynchronous functions, one way is to define a “waterfall then”:

2c-async-chain.html
// (C) ASYNC CHAIN
add(2,3)
.then(added => {
  console.log(added); // 5
  multiply(added, 5)
  .then(multiplied => console.log(multiplied)); // 25
});

 

AWAIT

2d-await.html
// (A) ADD FUNCTION
async function add (first, second) {
  return first + second;
}
 
// (B) MULTIPLY FUNCTION
async function multiply (first, second) {
  return first * second;
}

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

I hear you – A “waterfall then” is stupid and confusing. So finally, introducing the await mechanism. This should be self-explanatory, wait for an asynchronous function to finish processing and return the result. But please take note, we can only use await in a async function.

 

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

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

 

ARROW FUNCTIONS

Just what are those () => {} things in the above examples? For those who missed it, those are called “arrow functions”.

  • You know this – function twice (a) { return a * 2; }
  • We can also do this – var twice = function (a) { return a * 2; };
  • Shorthand it to an arrow function – var twice = (a) => { return a * 2; };
  • We can further simplify “single parameter single line” functions –  var twice = a => a * 2;

 

OTHER ASYNCHRONOUS MECHANISMS

Before we end, here’s a quick note and disclaimer – async function is not the only asynchronous mechanism in Javascript. The other common ones are:

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

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

 

SYNCHRONOUS BLOCKING PROBLEM

Synchronous Javascript works just fine, why do we even need “asynchronous Javascript”!? It’s messy and confusing. I know, but the exact problem with synchronous is what we call “blocking”. Where one massive process becomes the bottleneck and stops the rest from working. A simple example:

  • Synchronous – The user will have to stare at a “now loading spinner” while the script processes a massive file and sends it to the server for saving.
  • Asynchronous – Periodic processing and saving happen in the background. The user can work on the project uninterrupted.

Yep, asynchronous Javascript (and coding in general) is here for good reasons.

 

COMPATIBILITY CHECKS

Asynchronous Javascript is nothing new… It is already well supported in all modern browsers at the time of writing.

 

LINKS & REFERENCES

 

INFOGRAPHIC CHEAT SHEET

Synchronous Asynchronous Javascript (Click to Enlarge)

 

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 *