JavaScript Tutorial
Estimated reading: 4 minutes 11 views

๐Ÿงต Asynchronous JavaScript โ€“ Callbacks, Promises & Async/Await


๐Ÿงฒ Introduction โ€“ Why Learn Asynchronous JavaScript?

In JavaScript, asynchronous programming allows us to perform long-running tasks (like fetching data or waiting for a timeout) without blocking the main thread. Without async logic, your app would freeze every time it waits for an external operation.

๐ŸŽฏ In this guide, you’ll learn:

  • How asynchronous JavaScript works
  • Core concepts: Callbacks, Promises, and async/await
  • The Event Loop and Microtasks
  • Practical async functions like setTimeout() and setInterval()
  • Promisification and promise chaining

๐Ÿ“˜ Topics Covered

๐Ÿ”น Topic๐Ÿ“„ Description
JavaScript CallbacksBasic async via functions
JavaScript PromisesModern, cleaner async handling
JavaScript Async/AwaitAsync syntax with sync style
PromisificationConvert callbacks to promises
setTimeout/setIntervalDelay and interval functions
Microtasks & ChainingEfficient async queuing

๐Ÿ” JavaScript โ€” Callbacks

๐Ÿ“Œ What is a Callback?

A callback is a function passed as an argument to another function, often used for async logic like reading files or making HTTP requests.

function greet(name, callback) {
  console.log("Hi " + name);
  callback();
}

greet("Alice", () => console.log("Greeting completed"));

โ— Problems with Callbacks

  • Hard to manage multiple levels โ†’ callback hell
  • Difficult to read and debug

๐ŸŒŸ JavaScript โ€” Promises

๐Ÿ“Œ What is a Promise?

A Promise is an object representing the eventual completion or failure of an async task.

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

promise.then(result => console.log(result));

โœ… States of a Promise

  • Pending โ†’ initial state
  • Fulfilled โ†’ resolve()
  • Rejected โ†’ reject()

โšก JavaScript โ€” Async/Await

๐Ÿ“Œ What is async/await?

Built on top of Promises, async/await allows you to write asynchronous code like synchronous code.

async function fetchData() {
  let response = await fetch("https://api.example.com");
  let data = await response.json();
  console.log(data);
}

๐Ÿ”„ Benefits

  • Cleaner syntax
  • Better error handling with try...catch
  • Easier to chain and debug

๐Ÿงฑ JavaScript โ€” Promisification

๐Ÿ“Œ What is Promisification?

Promisification means converting callback-based APIs to return Promises.

Example:

function wait(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

wait(1000).then(() => console.log("Waited 1 second"));

Use it to upgrade old codebases to Promise/async style.


๐Ÿช JavaScript โ€” Microtasks & Chaining

๐Ÿ“Œ Microtasks Queue

  • Tasks from .then(), catch(), finally(), and async/await
  • Run after the current call stack and before setTimeout()
console.log("Start");
Promise.resolve().then(() => console.log("Microtask"));
setTimeout(() => console.log("Macrotask"), 0);
console.log("End");

Output:

Start
End
Microtask
Macrotask

โฑ JavaScript โ€” setTimeout / setInterval

๐Ÿ•’ setTimeout()

Executes a function after a delay.

setTimeout(() => console.log("Runs after 1 sec"), 1000);

๐Ÿ” setInterval()

Repeats a function at intervals.

setInterval(() => console.log("Runs every 2 sec"), 2000);

๐Ÿ›‘ Note: Use clearTimeout() and clearInterval() to stop them.


๐Ÿ“Œ Summary โ€“ Recap & Next Steps

Asynchronous JavaScript is at the heart of modern web development. Mastering it will help you build fast, responsive apps, avoid blocking issues, and write more maintainable code.

๐Ÿ” Key Takeaways:

  • Callbacks are simple but messy for deep async logic
  • Promises simplify chaining and error handling
  • async/await makes code easier to write and understand
  • Understand Microtask queues and Promisification for full control

โš™๏ธ Real-World Relevance:
From frontend apps to backend APIs in Node.js, async programming is everywhere. It’s essential for scalability, UX, and modern development workflows.


โ“ FAQs

Q1: What is the difference between setTimeout() and Promises?

โœ… setTimeout() schedules a delay, while Promises handle future results of async operations. Promises are more flexible for chaining and error handling.


Q2: Can async/await replace all Promises?

โœ… async/await is syntactic sugar built on top of Promises. It makes them easier to use, but it doesnโ€™t replace them.


Q3: What is a Microtask in JavaScript?

โœ… A Microtask is a short function like a .then() callback scheduled after the current function completes but before any macrotasks (setTimeout).


Q4: Why is “callback hell” problematic?

โœ… Callback hell leads to deeply nested code that’s hard to read, maintain, and debug. Promises or async/await solve this issue.


Q5: What does await do?

โœ… await pauses the function execution until the Promise is resolved or rejected.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

๐Ÿงต Asynchronous JavaScript

Or Copy Link

CONTENTS
Scroll to Top