How to Handle Asynchronous JavaScript – Callbacks, Promises, and Async/Await

Asynchronous JavaScript: A Real-World Analogy

Imagine ordering food at a restaurant. You place your order, and the chef starts preparing it. Meanwhile, you don’t just stand there waiting; you take a seat, maybe check your phone, or chat with friends. When your food is ready, the waiter brings it to you. This is similar to how asynchronous JavaScript works.

Callbacks: The Waiter Approach

Callbacks are like telling the waiter, “when my food is ready, please let me know.” You pass a function(the callback) to another function, which executes it when a specific task is completed.

Technical definition: A callback is a function that is passed as an argument to another function, with the intention of being executed by the latter function when a specific task or operation is completed. The callback function is invoked with the result of the operation, allowing the outer function of the outcome.

Example :

function orderFood(callback) {
  setTimeout(() => {
    callback("Food is ready!");
  }, 2000);
}

orderFood((message) => {
  console.log(message);
});

//Output: Food is ready!

In the above example the orderFood function takes a callback function as an argument and executes it after a 2-second delay using setTimeout. When the delay is over, the callback function logs “Food is ready!” to the console.

Promises: The Receipt Approach

Promises are like the receiving a receipt with an order number. You can use this receipt to track the status of your order. Promises represent the eventual completion or failure of an asynchronous task.

Technical Definition: A promise basically is an object that represents the eventual completion or failure of an asynchronous operation. It provides an way to handle the outcome of the operation, which allowing you to execute code when the operation is completed or failed.

Example :

function orderFood() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("Food is ready!");
    }, 2000);
  });
}

orderFood()
  .then((message) => {
    console.log(message);
  })
  .catch((error) => {
    console.error("Error:", error);
  });

//output: Food is ready!

In the above example the orderFood function returns a promise that resolves with “Food is ready!” after a 2-second delay. The .then() method handles the resolved value, logging it to the console, while .catch() handles any potential errors.

Async/Await: The Simplified Approach

Async/await it’s is like a more convenient way to order food. You can simply tell the waiter, “I’ll have this,” and they’ll handle the rest. Async/await allows you to write asynchronous code that looks synchronous.

Technical Definition: Async/await it’s a syntax sugar on top of promises that allows you to write asynchronous code that is easier to read and maintain. It provides a way to pause the execution of a function until a promise is resolved or rejected, allowing you to write code that looks synchronous.

Example :

async function orderFood() {
  try {
    const message = await new Promise((resolve) => {
      setTimeout(() => {
        resolve("Food is ready!");
      }, 2000);
    });
    console.log(message);
  } catch (error) {
    console.error("Error:", error);
  }
}

orderFood();

//output: Food is ready!

In the above example the orderFood function uses await to pause execution until the promise is resolved, then logs “Food is ready!” to the console. The try-catch block handles any potential errors that might occur during the promise resolution.

 

 

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top