Asynchronous JavaScript

JavaScript is single-threaded, meaning it executes code sequentially. Asynchronous JavaScript allows tasks to run independently of the main thread, enabling non-blocking operations such as fetching data, timers, and event handling.

Illustration of asynchronous_javascript
Illustration of asynchronous_javascript

💡 Why Asynchronous?

Asynchronous code prevents the UI from freezing by allowing long-running tasks (like network requests) to run in the background.

Core Concepts

  • Callbacks: Functions passed as arguments to be executed later.
  • Promises: Objects representing eventual completion or failure of async operations.
  • Async/Await: Syntax sugar to write asynchronous code that looks synchronous.

1. Callbacks

Callbacks are the oldest way to handle async code. A function is passed as an argument and called when the async task finishes.

📌 Deep Dive: Callback Example

JAVASCRIPT
function fetchData(callback) {
  setTimeout(() => {
    callback('Data loaded');
  }, 1000);
}

fetchData(message => {
  console.log(message);
});
Output
Data loaded

⚠️ Callback Hell

Multiple nested callbacks can lead to hard-to-read and maintain code, known as "callback hell."

2. Promises

Promises represent a value that may be available now, later, or never. They have three states: pending, fulfilled, or rejected.

📌 Deep Dive: Promise Example

JAVASCRIPT
const fetchData = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Data loaded via Promise');
  }, 1000);
});

fetchData.then(message => console.log(message));
Output
Data loaded via Promise

3. Async/Await

Async/await is syntactic sugar over promises, allowing you to write asynchronous code that looks synchronous, improving readability.

📌 Deep Dive: Async/Await Example

JAVASCRIPT
function fetchData() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('Data loaded with async/await');
    }, 1000);
  });
}

async function getData() {
  const message = await fetchData();
  console.log(message);
}

getData();
Output
Data loaded with async/await
Comparison: Callbacks vs Promises vs Async/Await
FeatureCallbacksPromisesAsync/Await
SyntaxNested functionsThen/catch chainsLooks synchronous
Error HandlingManual and complexUsing .catch()Try/catch blocks
ReadabilityPoor with nestingImprovedBest, clean code
Control FlowDifficultBetter with chainingVery intuitive

💡 Event Loop Overview

The event loop manages asynchronous operations by handling the call stack and task queue, ensuring async callbacks execute after the current execution completes.

⚠️ Avoid Blocking Code

Heavy synchronous tasks block the event loop and freeze interfaces. Use asynchronous patterns to keep apps responsive.