Browse Categories
Choose your Categories to read

Synchronous and Asynchronous Javascript

Malay Gain
Dec 2, 2021

 

Introduction

Synchronous and Asynchronous behavior of javascript makes the language more efficient. Here synchronous means executing sequentially, and asynchronous means executing code immediately.

Let’s dive into more to visualize these behaviors.

Source: Quora

 

Synchronous javascript

Every statement in a function executes sequentially. Similarly, for multiple functions, it follows the same behavior. A call stack is maintained to execute the functions sequentially. This is the synchronous part of javascript, where its main thread makes sure that it will take care of execution order in a sequential manner.

 

Example code

function f1(){
  console.log("it is my 1st function)");
}

function f2(){
  console.log("it is my 2nd function)");
  f1();
}

f2();

 

Output

it is my 2nd function
it is my 1st function

 

When the f2() function is called, console.log() is executed first, and then f1(). So, the execution order is sequential here.

Asynchronous javascript

Executing things in sequence works well in javascript. But especially those operations that access or fetch some resource from a server, such as fetching a file from the network, accessing a database and returning data from it, accessing a video stream from a webcam, or execute a function with a delay, the result of such operations can't be returned immediately. Sometimes it is unknown how much time it will take to fetch from a server, or it needs to execute after a specified time.

But what if we may not want the javascript engine to halt the execution of the other sequential code. So, the javascript engine needs to manage things a bit more efficiently in this case and execute asynchronously.

Most asynchronous javascript operations are two types.

 

  • Browser API/Web API events or functions: This type includes event handlers like click, mouse over, scroll, etc., and methods like setTimeout.

 

  • Promises: It is a unique javascript object that allows us to perform asynchronous operations.

 

 

Asynchronous callbacks in Browser API/Web API events or functions: 

Browser APIs like event handlers and setTimeout depend on callback functions. A callback function executes after an asynchronous operation finishes. Here we will discuss an example of how a setTimeout function executes with callback function:

setTimeout(() =>{console.log("this is the 1st callback")}, 3000);

setTimeout(() => {console.log("this is the 2nd callback")}, 2000);

 

Output:

this is the 2nd callback
this is the 1st callback

 

Being asynchronous setTimeout function will not pause execution of other functions in the call stack. That’s why the 2nd callback is executed before the 1st callback.

 

Promises:

Promises are the new style of asynchronous code that is used in modern Web APIs. The fetch() API is a good example, which is basically like a modern, more efficient version of XMLHttpRequest. Let's look at a quick example of fetching data from the server:

fetch('https://example.com/profile')
.then(response => response.json())
.then(data => {
  console.log('Success:', data);
})
.catch((error) => {
  console.error('Error:', error);
});

 

In the above code, fetch() is a method, taking a parameter, the URL of a resource you want to access from the server and returning a promise object. This promise is an object signifying the completion or failure of the asynchronous operation. In browser's words, it is like "I promise to get back to you with the answer as soon as I am done," hence the name "promise."

The fetch method is currently waiting on the result of the browser trying to complete the HTTP request. There are three further code blocks chained with the fetch() method.

If the HTTP request is successful, two then() blocks both contain a callback function that will run to resolve the response object. The catch() block will run if any of the .then() blocks fail . But synchronous try...catch won't work with promises.

Asynchronous operations like promises instead of call stack are put into the event queue, which runs after the program in the above codeFetch ’s main thread finished processing so that they do not block subsequent javaScript code from running. 

  

FAQs

  1. What is the callback?
    It is actually a function used as an argument for another function. A callback can be synchronous as well as asynchronous.
     
  2. What are promises?
    It is a unique javascript object that denotes the completion and failure of asynchronous operations.
     
  3. What is browser API?
    Web or browser API is an API  provided by the browser that can be used to communicate with the browser using javascript.
    E.g., DOM API for manipulating documents, Fetch API for fetching data from the server.
     
  4. What is the main difference between callback and promise?
    A callback is a function, whereas a promise is an object returned by an asynchronous operation.
     
  5. What is an event?
    Here event means a web or browser event which is defined as part of web APIs.Some common events are click, mouseover, mouseout, mousedown, etc.

Key Takeaways

This article discussed the concept of Synchronous and Asynchronous javascript. The blog also tried to describe promises and callbacks in javascript.

To learn more, head over right now to Coding Ninjas to practice important javascript interview problems and crack your interviews like a Ninja!

Happy learning!

Was this article helpful ?
0 upvotes