What is Difference Between Callbacks, Promises and Async/Await in Javascript

Callbacks, Promises, and Async/Await are three ways to handle asynchronous code in JavaScript. Understanding the differences between them can be useful in writing efficient and maintainable code. In this tutorial, we’ll explore the differences between these three concepts.

Callbacks

A callback is a function that is passed as an argument to another function and is called when the operation is complete. Callbacks are used to handle asynchronous operations in JavaScript. When an asynchronous operation is initiated, a callback function is passed as an argument to the function that starts the operation. Once the operation is complete, the callback function is called with the result.

The main disadvantage of callbacks is that they can lead to “callback hell,” which is when code becomes difficult to read and maintain because of the nested callbacks. Additionally, error handling can be difficult with callbacks.

Here’s an example of a callback function:

function getData(callback) {
  setTimeout(() => {
    callback('Data received');
  }, 2000);
}

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

Promises

A promise is an object that represents a value that may not be available yet, but will be at some point in the future. Promises can be in one of three states: pending, fulfilled, or rejected. Promises are used to handle asynchronous operations and to avoid callback hell.

Here’s an example of a Promise:

function getData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('Data received');
    }, 2000);
  });
}

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

Async/Await

Async/Await is a new way of writing asynchronous code in JavaScript. It is built on top of Promises and provides a more elegant way of handling asynchronous operations. With Async/Await, we can write asynchronous code that looks and behaves like synchronous code.

Here’s an example of using Async/Await:

async function getData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('Data received');
    }, 2000);
  });
}

async function fetchData() {
  try {
    const data = await getData();
    console.log(data);
  } catch (error) {
    console.log(error);
  }
}

fetchData();

In the above code, we define two functions. The getData() function returns a Promise that resolves with the data after 2 seconds. The fetchData() function is an Async function that waits for the getData() Promise to resolve, and then logs the data to the console.

In conclusion, callbacks, Promises, and Async/Await are all ways of handling asynchronous code in JavaScript. Callbacks are the oldest and simplest way of handling asynchronous code, while Promises and Async/Await provide more elegant and maintainable ways of handling asynchronous code.