Synchronous and Asynchronous in JavaScript


Synchronous and Asynchronous are two ways of executing code in JavaScript.

Synchronous Execution:

In synchronous execution, the code is executed in a sequential manner. Each line of code is executed one after the other, and the next line of code cannot be executed until the current line of code has finished executing. This means that if there is a long-running task, such as a network request or a file read, the entire program will be blocked until that task is completed.

Example:

console.log("Start");

for (let i = 0; i < 1000000000; i++) {
  // Long running task
}

console.log("End");

In the above example, the program will print "Start", then execute the for loop, which is a long-running task, and then print "End". The entire program will be blocked until the for loop is completed.

Asynchronous Execution:

In asynchronous execution, the code is executed in a non-sequential manner. Each line of code is not executed one after the other, and the next line of code can be executed before the current line of code has finished executing. This means that if there is a long-running task, such as a network request or a file read, the program will not be blocked, and other code can be executed while the task is being performed.

Example:

console.log("Start");

setTimeout(() => {
  console.log("Async Task");
}, 1000);

console.log("End");

In the above example, the program will print "Start", then execute the setTimeout function, which is an asynchronous task that will execute after 1 second, and then print "End". The program will not be blocked while the setTimeout function is waiting to execute, and other code can be executed in the meantime.

Methods for Asynchronous Execution:

There are several methods for asynchronous execution in JavaScript:

  • Callbacks: A callback is a function that is passed as an argument to another function and is executed when the other function has completed its task.

Example:

function fetchData(callback) {
  setTimeout(() => {
    const data = { name: "John", age: 30 };
    callback(data);
  }, 1000);
}

fetchData((data) => {
  console.log(data);
});

In the above example, the fetchData function is an asynchronous function that takes a callback function as an argument. The callback function is executed when the fetchData function has completed its task.

  • Promises: A promise is an object that represents the eventual completion or failure of an asynchronous operation and its resulting value.

Example:

function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const data = { name: "John", age: 30 };
      resolve(data);
    }, 1000);
  });
}

fetchData()
  .then((data) => {
    console.log(data);
  })
  .catch((error) => {
    console.log(error);
  });

In the above example, the fetchData function returns a promise object. The then method is used to handle the successful completion of the promise, and the catch method is used to handle any errors that may occur.

  • Async/Await: Async/await is a newer way of handling asynchronous code in JavaScript. It allows you to write asynchronous code that looks like synchronous code.

Example:

async function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const data = { name: "John", age: 30 };
      resolve(data);
    }, 1000);
  });
}

async function main() {
  console.log("Start");
  const data = await fetchData();
  console.log(data);
  console.log("End");
}

main();

In the above example, the fetchData function returns a promise object, and the main function uses the await keyword to wait for the promise to be resolved before continuing execution. The main function looks like synchronous code, but it is actually asynchronous.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.