Skip to main content

Command Palette

Search for a command to run...

Synchronous vs Asynchronous JavaScript

Updated
4 min read

What are we gonna study?

Today, we are going to study about topics that are given below:

  1. What synchronous code means

  2. What asynchronous code means

  3. Why JavaScript needs asynchronous behavior

  4. Problems that occur with blocking code

So, today's session is all about Sync VS Async, trust me there would be no doubts after this, you just have to do 3 things,

  1. Gather all your focus and attention from your crush to here.

  2. Sit back relaxed.

  3. Have a tea/coffee with you :)

With this let's begin!


What is Synchronous Code?

  • Basically, synchronous code is what you have written all the way till now in JavaScript :)

  • But if you have never written here is an example:

const character = 'Naruto'

if (character === 'Naruto') {
  console.log('Dattebayo!')
}
  • This is your synchronous code, it basically executes one by one.

  • The main thread (JavaScript is a single threaded language and that thread is known as main thread) runs line by line and does one task at a time.

  • That is all your synchronous code.


What is Asynchronous Code

  • Asynchronous simply means mulitple task at a time, where whenever it get completed, it gets executed.

  • If you have ever written code with callbacks, promises, async/await then tell me when do they get executed?Simply when there task get completed.

  • Is it definte that they will run in a sequence? Nah, never they never ever run in a definite sequence, then run when they finish doing whatever they are doing.

  • Read the below code as well as its comments to get more proper understanding over it:

// API Fetching must be Asynchronous because it might reply you after a second or even a minute so, fetch an api using asynchronous code and a api with synchronous code and see the reuslt

function syncFetch() {
  const data = fetch ("https://jsonplaceholder.typicode.com/todos/1");
  console.log(data);
}

async function asyncFetch() {
  const data = await fetch  ("https://jsonplaceholder.typicode.com/todos/1");
  console.log(data);
}

syncFetch();
// Promise<pending>

asyncFetch();
// Expected data from the API

We can clearly see that, Synchronous code just executed it didn't waited for the response it kept on executing what's in its way but Asynchronous code waited for the response of the API response.

That is the difference between Sync and Async.


Problems with blocking code

Blocking code is often made by Synchronous code let's first see in code that what a blocking code looks like, then you'll figure out the problem yourself.

// Example 1

for (let i = 0; i < 1000000000; i++) {
  console.log("She blocked me T-T");
}

console.log("This will only run AFTER the loop finishes");

// Example 2

const fs = require('fs');
const data = fs.readFileSync('/large-file.txt'); 
console.log('File content read. Now continuing...');

// Example 3

alert('She hates you')
console.log("This won't run until you click OK")

Can you see these blocking codes they won't run until the task is completed and that's not a problem at all.

Blocking code have their own use cases, Non-Blocking code have their own use cases, only thing that have no use case is you in her life :)


Wrap Up!

Look you reached the end and didn't even realised ask yourself that do you know the difference between Sync and Async in JavaScript? The answer should be yes!

i would love your feedbacks in the comment section, that's it for today!

I'll catch you up in the next blog until then keep coding and keep enjoying your tea/coffee (no debates there :) ) ☕💝

JavaScript: Everything you should know

Part 17 of 26

This is your ultimate guide towards JavaScirpt, this series of articles include - JavaScript Operators: The Basics You Need to Know - Understanding Variables and Data Types in JavaScript - Template Literals in JavaScript - Control Flow in JavaScript: If, Else, and Switch Explained - Array Methods You Must Know - JavaScript Arrays 101 - Function Declaration vs Function Expression: What’s the Difference? - Arrow Functions in JavaScript: A Simpler Way to Write Functions - Understanding Objects in JavaScript - Spread vs Rest Operators in JavaScript - Destructuring in JavaScript - Map and Set in JavaScript - Understanding Object-Oriented Programming in JavaScript - Understanding the this Keyword in JavaScript - The new Keyword in JavaScript - The Magic of this, call(), apply(), and bind() in JavaScript - Array Flatten in JavaScript - String Polyfills and Common Interview Methods in JavaScript - Synchronous vs Asynchronous JavaScript - Callbacks in JavaScript: Why They Exist - JavaScript Promises Explained for Beginners - Promise Methods Explained: CID Analogy - Async/Await in JavaScript: Writing Cleaner Asynchronous Code - Error Handling in JavaScript: Try, Catch, Finally - JavaScript Modules: Import and Export Explained - The Part of Events You Never See The following 26 articles and topics are covered

Up next

Async/Await in JavaScript: Writing Cleaner Asynchronous Code

What are we gonna Study? This blog is about one of the most important concept of JavaScript and trust me you would love it... Topics we are going to cover are: Why async/await was introduced How asy

More from this blog

L

Learning Tech

61 posts

A Blog with dozens of articles on different langauges as well as frameworks, This isn't just for you to learn, i crafted it thinking that this could be my future reference as well

It covers Networking, Web Development, Mobile Developement and very soon GenAI too!