what is the difference between call back, promises, and await async?

·

2 min read

Before explaining the difference,
first, we have to understand what they are and why we need these.

Callback, promises, and await async is the javascript concept that deals with the handling of an asynchronous task.

the callback is an old concept of javascript whereas promises came into existence in ES6 and async-await in ES8.

in promises and async-await its easy to catch error, readability, and avoid callback hell, easy to chain with multiple async functions.

Let us understand this with an example

// CallBack example
function fetchData(callback) {
  setTimeout(() => {
    const data = { name: "skyLTT", age: 30 };
    callback(data);
  }, 2000); // async operation
}

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

processData(); // Output: { name: "skyLTT", age: 30 }

// Promises example
function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const data = { name: "skyLTT", age: 30 };
      resolve(data);
    }, 2000);
  });
}

function processData() {
  fetchData()
    .then((data) => { // promises fullfill
      console.log(data);
    })
    .catch((error) => { // if any error 
      console.log(error);
    });
}

processData(); // Output: { name: "skyLTT", age: 30 }

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

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

processData(); // Output: { name: "skyLTT", age: 30 }

In general, both promises and async-await are good and widely used techniques for handling asynchronous programming in JavaScript, the use totally depends upon project requirements and personal preference.

I hope you found this blog useful. If so, please consider sharing it with your friends. If not, I would appreciate your feedback. You can also reach out to me on Twitter at @lalitaswal2, and I would be happy to hear your thoughts.