27.1 C
Pakistan
Saturday, July 27, 2024

Javascript callback functions

Callbacks are functions in JavaScript that are called from within other functions after being passed as arguments to them.

In asynchronous programming, callbacks are frequently used to handle operations like managing timers, handling events, and submitting API requests.

An illustration of a callback function

function doSomethingAsync(callback) {
  setTimeout(function() {
    console.log("Task done!");
    callback();
  }, 1000);
}

function callbackFunction() {
  console.log("Callback function executed");
}

doSomethingAsync(callbackFunction);

In this example, doSomethingAsync is a function that takes a callback function as an argument and uses setTimeout to simulate an asynchronous task. When the task is complete, the callback function (callbackFunction) is invoked.

Callbacks in Asynchronous Operations:

function fetchData(url, callback) {
  // Simulate an asynchronous API request
  setTimeout(function() {
    const data = { message: "Data fetched successfully" };
    callback(null, data); // First argument is an error (if any), and the second is the data
  }, 2000);
}

function handleData(error, result) {
  if (error) {
    console.error("Error:", error);
  } else {
    console.log("Result:", result);
  }
}

fetchData("https://api.example.com/data", handleData);

In this example, the callback function (handleData) is passed to fetchData, which mimics an asynchronous API request. The outcome or an error is then passed to the callback function.

ES6 As an Alternative: Promises

Even though callbacks are frequently used, ES6 brought Promises to make asynchronous code easier to write. Promises offer improved error handling and a cleaner syntax. As an illustration, consider this:

function fetchData(url) {
  return new Promise((resolve, reject) => {
    setTimeout(function() {
      const data = { message: "Data fetched successfully" };
      resolve(data);
      // Or, to simulate an error:
      // reject("Failed to fetch data");
    }, 2000);
  });
}

fetchData("https://api.example.com/data")
  .then(result => {
    console.log("Result:", result);
  })
  .catch(error => {
    console.error("Error:", error);
  });

.then() and.catch() can be used to chain promises in order to handle success and error cases, respectively.

Await/Async:

A syntactic sugar over promises, async/await was introduced in ES8 to make asynchronous code even more readable. Here’s an easy illustration:


async function fetchData(url) {
  return new Promise((resolve, reject) => {
    setTimeout(function() {
      const data = { message: "Data fetched successfully" };
      resolve(data);
      // Or, to simulate an error:
      // reject("Failed to fetch data");
    }, 2000);
  });
}

async function fetchDataAndHandle() {
  try {
    const result = await fetchData("https://api.example.com/data");
    console.log("Result:", result);
  } catch (error) {
    console.error("Error:", error);
  }
}

fetchDataAndHandle();

By enabling the writing of asynchronous code in a more synchronous manner, async/await further streamlines the syntax.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles