No announcement
 

Callback Functions, Async/Await and Promises

Callback Functions

Callback functions are functions that are passed as arguments to other functions. They are used to ensure that a certain function is executed only after another function has finished executing, usually to handle asynchronous operations.

Example:

callback_function.html

<!DOCTYPE html>
<html>
<head>
  <title>Callback Functions Example</title>
</head>
<body>

<h2>Callback Functions:</h2>
<button id="btn">Click Me</button>
<p id="output"></p>

<script>
document.getElementById("btn").addEventListener("click", function() {
  document.getElementById("output").textContent = "Loading...";
  fetchData(function(result) {
    document.getElementById("output").textContent = result;
  });
});

function fetchData(callback) {
  setTimeout(function() {
    callback("Data loaded!");
  }, 2000);
}
</script>

</body>
</html>

Output
When you click the "Click Me" button, the text "Loading..." will appear, and after 2 seconds, it will change to "Data loaded!".

Async/Await

Async/await is a modern approach to handling asynchronous operations in JavaScript. It allows you to write asynchronous code that looks synchronous, making it easier to understand and manage.

Example:

async_await.html

<!DOCTYPE html>
<html>
<head>
  <title>Async/Await Example</title>
</head>
<body>

<h2>Async/Await:</h2>
<button id="btn">Click Me</button>
<p id="output"></p>

<script>
document.getElementById("btn").addEventListener("click", async function() {
  document.getElementById("output").textContent = "Loading...";
  let result = await fetchData();
  document.getElementById("output").textContent = result;
});

async function fetchData() {
  return new Promise(resolve => {
    setTimeout(function() {
      resolve("Data loaded!");
    }, 2000);
  });
}
</script>

</body>
</html>

Output
When you click the "Click Me" button, the text "Loading..." will appear, and after 2 seconds, it will change to "Data loaded!".

Promises and Chaining Promises

Promises are a way to handle asynchronous operations in a more structured manner. Promises can be chained together to perform sequential asynchronous tasks.

Example:

promises.html

<!DOCTYPE html>
<html>
<head>
  <title>Promises and Chaining Example</title>
</head>
<body>

<h2>Promises and Chaining:</h2>
<button id="btn">Click Me</button>
<p id="output"></p>

<script>
document.getElementById("btn").addEventListener("click", function() {
  document.getElementById("output").textContent = "Loading...";
  fetchData()
    .then(result => {
      document.getElementById("output").textContent = result;
    })
    .catch(error => {
      document.getElementById("output").textContent = "Error occurred!";
    });
});

function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(function() {
      resolve("Data loaded!");
      // Uncomment the line below to simulate an error
      // reject("Error occurred!");
    }, 2000);
  });
}
</script>

</body>
</html>

Output
When you click the "Click Me" button, the text "Loading..." will appear, and after 2 seconds, it will change to "Data loaded!" if successful. If an error is simulated (by uncommenting the appropriate line), it will show "Error occurred!" instead.

Converting Promises to Async/Await

Promises can be easily converted to async/await syntax for cleaner and more readable code.

Example:

converting_promises.html

<!DOCTYPE html>
<html>
<head>
  <title>Converting Promises to Async/Await Example</title>
</head>
<body>

<h2>Converting Promises to Async/Await:</h2>
<button id="btn">Click Me</button>
<p id="output"></p>

<script>
document.getElementById("btn").addEventListener("click", async function() {
  document.getElementById("output").textContent = "Loading...";
  try {
    let result = await fetchData();
    document.getElementById("output").textContent = result;
  } catch (error) {
    document.getElementById("output").textContent = "Error occurred!";
  }
});

function fetchData() {
  return new Promise(resolve => {
    setTimeout(function() {
      resolve("Data loaded!");
    }, 2000);
  });
}
</script>

</body>
</html>

Output
The output behavior is similar to the "Async/Await" example.

Callback functions, async/await, and promises are essential concepts for handling asynchronous operations in JavaScript. Callbacks are a traditional approach, while promises and async/await are more modern and help manage asynchronous code more effectively, making it easier to read and understand.