Learning Objectives
- Predict exact execution order across synchronous logs, `Promise.then`, `queueMicrotask`, and `setTimeout`.
- Avoid accidental sequential `await` waterfalls when independent API requests can execute concurrently.
- Handle failures cleanly with `try/catch` and `Promise.allSettled`.
Prerequisites
- JavaScript functions, callbacks, and ES6 arrow functions
Call Stack, Microtasks & Timers
JavaScript executes one synchronous frame at a time on a single thread. Whenever asynchronous work finishes, callbacks enter either the Microtask Queue (Promise.then, await continuations, queueMicrotask) or a Task / Macrotask Queue (setTimeout, DOM clicks, network I/O).
After every synchronous script turn empties the Call Stack, the Event Loop drains every single queued Microtask before advancing to the next Macrotask timer.
Apply these fundamentals cleanly in React Hooks or Node.js Express Middleware, and explore our Frontend Developer Career Program.
Practical Programming Examples
Predicting Event Loop Execution Order & Concurrent Fetching
Verify why Promise microtasks flush before setTimeout(0) callbacks and execute two fetches concurrently.
console.log('1: sync start');
setTimeout(() => console.log('4: macrotask timeout'), 0);
Promise.resolve().then(() => console.log('3: microtask promise'));
console.log('2: sync end');
async function loadDashboard() {
const [profile, mocks] = await Promise.all([
Promise.resolve({ name: 'Aarav' }),
Promise.resolve({ passed: 12 }),
]);
return { profile, mocks };
}
loadDashboard();
1: sync start 2: sync end 3: microtask promise 4: macrotask timeout
- All top-level synchronous `console.log` statements run first (`1: sync start`, `2: sync end`).
- Once the call stack empties, the microtask queue flushes (`3: microtask promise`).
- Only after all microtasks clear does the Event Loop pick `setTimeout(..., 0)` (`4: macrotask timeout`).
Common Mistakes to Avoid
- Writing `const a = await fetchA(); const b = await fetchB();` sequentially when `a` and `b` are independent (`Promise.all` halves latency).
- Using `async/await` inside `Array.prototype.forEach()` — `forEach` fires callbacks concurrently and ignores awaited promises.
Production Best Practices
- Use `for...of` for intentional sequential async iteration and `Promise.all` / `Promise.allSettled` for bounded concurrency.
- Cancel stale `fetch` requests cleanly with `AbortController`.
Technical Interview Relevance
Almost every Indian service MNC and product frontend interview starts with an Event Loop output prediction problem.
Practice & Self-Check Questions
Why does `array.forEach(async (item) => { await save(item); })` exit before items finish saving?
`Array.prototype.forEach` invokes the callback synchronously without awaiting returned Promises; use `for (const item of array)` for sequential awaits or `await Promise.all(array.map(...))` for concurrent completion.