Asynchronous JavaScript

JavaScript is a single-threaded, synchronous language by default. It executes one task at a time in sequence. Without asynchronous features, any long-running task (like fetching data from a server or waiting for user input) would block the main thread, causing the web page to freeze.

Asynchronous JavaScript solves this problem by allowing tasks to run in the background without blocking the main execution flow.

Core Concepts:

Analogy: Think of a chef (JS engine) cooking meals. If a dish takes time (async task), the chef delegates it to an assistant (Web APIs). Once it’s ready, the assistant notifies the chef, who serves it when free (Event Loop).

1. setTimeout & setInterval

Timers are the simplest form of asynchronous behavior in JavaScript:

Syntax:

// Run once after a delay setTimeout(callback, delay); // Run repeatedly const id = setInterval(callback, interval); // Cancel a scheduled interval clearInterval(id);

2. Callbacks

A callback is a function passed into another function as an argument, to be executed later. This makes it possible to run code asynchronously (after some task completes).

Syntax:

function task(param, callback) { // do something callback(); // run after task completes }

3. Promises (.then, .catch, .finally)

A Promise is an object that represents the eventual result of an asynchronous operation. It can be in one of three states:

Syntax:

const promise = new Promise((resolve, reject) => { if (success) resolve(value); else reject(error); }); promise .then(result => { ... }) // handle success .catch(error => { ... }) // handle error .finally(() => { ... }); // always executes

4. async/await

Introduced in ES2017, async/await is syntactic sugar over Promises. async makes a function return a Promise. await pauses execution inside the function until the Promise resolves or rejects.

Syntax:

async function functionName() { try { const result = await somePromise; return result; } catch (error) { // handle error } }

5. fetch API

fetch() is a modern, built-in API for making HTTP requests. It always returns a Promise, which resolves to a Response object.

Syntax:

fetch(url, options) .then(response => response.json()) .then(data => { ... }) .catch(error => { ... });