J

JavaScript Handbook

Clean • Professional

Asynchronous JavaScript – Overview

2 minute

Asynchronous JavaScript Overview

Asynchronous JavaScript allows code to run without blocking the main thread. It enables the execution of time-consuming tasks (like API calls, timers, or file reads) in the background, while the rest of the code continues running.

Callbacks

A callback is a function passed as an argument to another function, to be executed once an asynchronous operation completes.

Example:

setTimeout(() => console.log("Delayed"), 1000);
console.log("Immediate"); // Runs first

Callbacks are simple but can lead to callback hell — deeply nested functions that are hard to maintain.

Example: Callback Hell

setTimeout(() => {
  console.log("Step 1");
  setTimeout(() => {
    console.log("Step 2");
    setTimeout(() => console.log("Step 3"), 1000);
  }, 1000);
}, 1000);

Promises

A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation.

Promise States:

  • Pending: Initial state, neither fulfilled nor rejected.
  • Fulfilled: The operation completed successfully.
  • Rejected: The operation failed.

Core Methods:

  • .then(result => ...) → Handles successful completion.
  • .catch(error => ...) → Handles errors.
  • .finally(() => ...) → Executes regardless of the result.

Example:

const promise = new Promise((resolve, reject) => {
  setTimeout(() => resolve("Success"), 1000);
});

promise
  .then(result => console.log(result))   // "Success"
  .catch(error => console.log(error))
  .finally(() => console.log("Done"));

Promise Chaining:

fetch("<https://api.example.com/data>")
  .then(response => response.json())
  .then(data => console.log("Data:", data))
  .catch(error => console.log("Error:", error));

Async / Await

async/await is syntactic sugar built on top of Promises, allowing you to write asynchronous code that looks synchronous.

  • async → Declares a function that returns a Promise.
  • await → Pauses execution until the Promise resolves.

Example:

async function fetchData() {
  try {
    const response = await fetch("<https://api.example.com/data>");
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.log("Error:", error);
  }
}

fetchData();

Timers

Timers are one of the simplest asynchronous mechanisms.

FunctionDescription
setTimeout(callback, delay)Runs a function once after a delay (in ms).
setInterval(callback, delay)Runs a function repeatedly at intervals.
clearTimeout(id)Cancels a timeout.
clearInterval(id)Cancels an interval.

Example:

const id = setTimeout(() => console.log("Hello"), 1000);
clearTimeout(id); // Cancels the timeout

Event Listeners

Event listeners handle user or system events asynchronously, such as clicks, keystrokes, or network events.

Example:

document.getElementById("myButton").addEventListener("click", () => {
  console.log("Button clicked");
});

Common Asynchronous APIs

APIDescription
fetch()Makes HTTP requests and returns a Promise.
XMLHttpRequestLegacy HTTP API (older alternative to fetch).
Web APIsTimers (setTimeout), animation (requestAnimationFrame), etc.
FileReaderReads files asynchronously (in browsers).
Node.js APIsAsynchronous I/O operations like fs.readFile.

Example:

fetch("<https://api.example.com/data>")
  .then(res => res.json())
  .then(console.log);

Summary Table

MechanismDescriptionExample
CallbacksFunctions executed after completionsetTimeout(cb, 1000)
PromisesHandle async results & errorsfetch(...).then(...)
Async/AwaitPromise-based syntax simplifierawait fetch(...)
TimersSchedule delayed or repeated taskssetInterval(...)
Event ListenersReact to user/system eventsaddEventListener(...)

 

Article 0 of 0