JS Tutorial



JS ASYNCHRONOUS


JavaScript Asynchronous Programming

Asynchronous programming allows your code to execute operations without blocking the main thread, enabling non-blocking execution and better performance, especially in operations like I/O (e.g., file reading, network requests).

🔼 Why Asynchronous Programming?

Asynchronous operations allow your JavaScript code to perform time-consuming tasks like HTTP requests, file processing, or waiting for user input without freezing the browser or server. This is crucial for creating smooth and responsive applications.

🔼 Callback Functions

A callback function is a function that is passed as an argument to another function and is executed after the completion of an asynchronous task.

// Example 1: Using Callback Function
function fetchData(callback) {
  setTimeout(() => {
    console.log("Data fetched!");
    callback();
  }, 2000);
}

function processData() {
  console.log("Processing data...");
}

fetchData(processData);

🔼 Promises

A Promise represents the eventual completion or failure of an asynchronous operation. It allows chaining of asynchronous tasks, helping to avoid callback hell.

// Example 2: Using Promises
function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log("Data fetched!");
      resolve("Data");
    }, 2000);
  });
}

fetchData()
  .then((data) => {
    console.log(data); // "Data"
    console.log("Processing data...");
  })
  .catch((error) => {
    console.log("Error:", error);
  });

🔼 Async/Await

async/await is a modern way to handle asynchronous operations, making asynchronous code easier to read and write. It is built on top of promises.

// Example 3: Using Async/Await
async function fetchData() {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("Data fetched!");
      resolve("Data");
    }, 2000);
  });
}

async function processData() {
  const data = await fetchData();
  console.log(data); // "Data"
  console.log("Processing data...");
}

processData();

🎮 Interactive Example

Click to see how asynchronous programming works with Promises:

📘 Summary

  • Callback Functions: Functions passed as arguments to other functions, executed after the task completes.
  • Promises: Objects representing the eventual completion (or failure) of an asynchronous operation, with the ability to chain tasks.
  • Async/Await: A cleaner syntax for handling promises, allowing you to write asynchronous code that looks synchronous.
Tip: async/await is preferred for handling asynchronous tasks in modern JavaScript. It makes the code more readable and reduces nested callbacks.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review