Deep Dive: JavaScript Event Loop, Promises, and Async/Await Under the Hood

Understand microtasks, macrotasks, call stack execution, and how modern JavaScript handles non-blocking asynchronous I/O.

Deep Dive: JavaScript Event Loop, Promises, and Async/Await Under the Hood

JavaScript is single-threaded: it has one call stack and can only perform one instruction at any given time. Yet web applications seamlessly handle network requests, timers, animations, and user interactions without freezing the interface. How is this possible?

1. The Engine Architecture & The Event Loop

The magic relies on the host environment (the browser or Node.js runtime) providing background threads and orchestrating two distinct queues:

Microtask Queue

Has highest execution priority. Processed immediately after the current synchronous script finishes, before any rendering or macrotasks.

  • Promise.then() / .catch() / .finally()
  • queueMicrotask()
  • MutationObserver callbacks
Macrotask (Task) Queue

Scheduled by external APIs. The Event Loop picks one macrotask from this queue after exhausting all pending microtasks.

  • setTimeout() / setInterval()
  • requestAnimationFrame() (browser render)
  • I/O and DOM event callbacks

2. Classic Execution Order Puzzle

Predict the exact console output of this script to verify your mental model of the event loop:

event_loop_quiz.js
console.log("1. Synchronous Start");

setTimeout(() => {
    console.log("2. Macrotask: setTimeout 0ms");
}, 0);

Promise.resolve().then(() => {
    console.log("3. Microtask: Promise Callback 1");
}).then(() => {
    console.log("4. Microtask: Promise Callback 2");
});

queueMicrotask(() => {
    console.log("5. Microtask: queueMicrotask");
});

console.log("6. Synchronous End");
Output & Explanation
1. Synchronous Start
6. Synchronous End
3. Microtask: Promise Callback 1
5. Microtask: queueMicrotask
4. Microtask: Promise Callback 2
2. Macrotask: setTimeout 0ms

Why? Synchronous code finishes first (1, 6). Next, the engine drains all Microtasks (3, 5, 4). Only once the Microtask Queue is completely empty does the Event Loop move to the Macrotask Queue (2).

3. Production-Ready Async/Await with Error Boundaries

async/await is syntactic sugar built on top of native generator functions and Promises. Always encapsulate network operations within try...catch...finally blocks:

api_fetcher.js
/**
 * Robust asynchronous fetch with timeout and exponential backoff
 */
async function fetchWithRetry(url, options = {}, retries = 3, backoff = 500) {
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), options.timeout || 8000);
    
    try {
        const response = await fetch(url, { ...options, signal: controller.signal });
        
        if (!response.ok) {
            throw new Error(`HTTP Error ${response.status}: ${response.statusText}`);
        }
        
        return await response.json();
    } catch (err) {
        if (retries > 0) {
            console.warn(`Fetch failed (${err.message}). Retrying in ${backoff}ms...`);
            await new Promise(res => setTimeout(res, backoff));
            return fetchWithRetry(url, options, retries - 1, backoff * 2);
        }
        throw err;
    } finally {
        clearTimeout(timeoutId);
    }
}

Discussion (0)

Leave a Thought or Question

No comments posted yet. Be the first to start the discussion!