M O D U L E

Module 6: Asynchronous JavaScript

Handling things that take time, without freezing the page

6.1 Callbacks

A callback is a function passed as an argument to another function, intended to be executed once an asynchronous operation completes. In early JavaScript, callbacks were the primary mechanism for asynchronous programming.

Figure 6.1: Asynchronous Callback Delegation Flow 1. Call Initiated setTimeout(cb, 1000) Hands off to Web APIs 2. Background Timer Timer counts down 1s Main thread stays free 3. Callback Runs Queued to Task Queue Executes on Call Stack

Figure 6.1: Asynchronous callbacks allow the main thread to continue processing while slow tasks wait in the background.

6.2 The Event Loop

Because JavaScript is single-threaded, it has only one Call Stack and can execute only one instruction at a time. The Event Loop coordinates asynchronous execution without freezing the browser UI.

Figure 6.2: The JavaScript Event Loop & Non-Blocking Concurrency Architecture Call Stack Runs single-thread JS fn() executing Global context Hand off Browser Web APIs • setTimeout / setInterval • fetch() / XHR Network • DOM Events (clicks) When done Task Queue Callbacks waiting in line cb1, cb2, cb3 (FIFO) THE EVENT LOOP If Call Stack is empty → pushes next callback

Figure 6.2: The browser handles network requests and timers in the background (Web APIs). When finished, callbacks wait in the queue until the Event Loop confirms the Call Stack is empty.

6.3 Promises

A Promise is a modern JavaScript object representing the eventual completion (or failure) of an asynchronous operation and its resulting value, replacing messy nested callbacks with clean chains.

Figure 6.3: JavaScript Promise Lifecycle and State Transitions Pending resolve(value) Fulfilled .then(data => ...) reject(error) Rejected .catch(err => ...)

Figure 6.3: A Promise starts in the Pending state, then permanently transitions to either Fulfilled (invoking .then()) or Rejected (invoking .catch()).

6.4 async / await

Introduced in ES2017, async and await provide syntactic sugar on top of Promises, allowing developers to write asynchronous code that reads like sequential synchronous statements.

Figure 6.4: async / await Execution Flow — Non-blocking Micro-pause async function fetchUser() { const res = await fetch(url); const data = await res.json(); } Under the Hood: • 'await' pauses ONLY this function • Browser UI & other tasks continue! • Desugars into standard Promises

Figure 6.4: await yields control back to the event loop until the awaited promise settles, without freezing the main thread.

MODULE COMPREHENSIVE QUIZ

Module 6 Final Quiz

Test your understanding across all 4 topics of this module with interview-grade questions, tricky edge cases, and code output predictions.

Take Module 6 Final Quiz →
Yukti Mascot