techStackGuru

Synchronous vs Asynchronous JavaScript


Synchronous

In synchronous programming, the code is executed sequentially and blockingly. Synchronous execution of code means each line is executed one after another, and the next line executes once the previous one has finished. It means that if there is a time-consuming operation, the entire execution will be paused until it is completed.

Example

console.log('One');
console.log('Two');
console.log('Three');
Output
One
Two
Three 

Asynchronous

Asynchronous programming refers to executing code non-blockingly, allowing multiple operations to run simultaneously. Asynchronous code does not wait for an operation to complete before moving onto the next line. Rather, it initiates the operation and executes the subsequent code.

Example

console.log('One');
// Wait for 1 seconds
setTimeout(() => console.log('Two'), 2000);
console.log('Three');
Output
One
Three
Two 

Example - Synchronous: Fetching Data from an API

console.log("Before API call");
const response = fetch("URL");
console.log("After API call"); 

Example - Asynchronous: Fetching Data from an API

console.log("Before API call");
fetch("URL")
  .then(response => {
    console.log("Inside API callback");
  });
console.log("After API call"); 

Example - Synchronous: Reading a File

console.log("Before file read");
const data = fs.readFileSync("file.txt", "utf-8");
console.log("After file read"); 

Example - Asynchronous: Reading a File

console.log("Before file read");
fs.readFile("file.txt", "utf-8", (err, data) => {
  console.log("Inside file callback");
});
console.log("After file read"); 

Example - Synchronous: Making Multiple API Requests

console.log("Before first API call");
const response1 = fetch("URL1");
console.log("After first API call");
console.log("Before second API call");
const response2 = fetch("URL2");
console.log("After second API call"); 

Example - Asynchronous: Making Multiple API Requests

console.log("Before first API call");
fetch("URL1")
  .then(response1 => {
    console.log("Inside first API callback");
    // The next code depends on the first response
    console.log("Before second API call");
    return fetch("URL2");
  })
  .then(response2 => {
    console.log("Inside second API callback");
  });
console.log("After first API call");