Skip to article content
FrontendXLesson 06 / 30

Asynchronous JavaScript and the Event Loop

Build a precise mental model of JavaScript values, scope, functions, objects, arrays and asynchronous behavior, then implement and debug real utilities from first principles instead of memorizing outputs.

intermediate · about 45 minutes · 6 exercises

  • Predict
  • Explain
  • Implement
  • Debug
  • Test
  • Interview

What you will be able to do

#
  • Trace the order of synchronous code, microtasks and timer callbacks.
  • Use promises and async/await with correct error handling.
  • Avoid unhandled rejections and missing awaits.

Overview

#

Single thread, many tasks

JavaScript runs your code on a single call stack. When the stack is empty, the event loop pulls the next task from a queue. Timers and I/O callbacks go into the macrotask queue. Promise callbacks and queueMicrotask callbacks go into the microtask queue. After each macrotask, the engine drains the entire microtask queue before running the next macrotask.

snippet.js
console.log('sync');
setTimeout(() => console.log('timer'), 0);
Promise.resolve().then(() => console.log('microtask'));
// sync, microtask, timer

Promises

A promise is a placeholder for a value that will exist later. It is pending, then fulfilled or rejected, and it settles only once. then schedules a callback for fulfillment, catch for rejection, and finally runs on either. Each then returns a new promise, which is how chaining works.

async and await

An async function always returns a promise. await pauses the async function until the awaited promise settles, without blocking the thread. Wrap awaited calls in try/catch to handle rejections, or return the promise and let the caller handle it.

Common async defects

Forgetting await leaves you holding a promise instead of a value. An unhandled rejection crashes modern runtimes. Running independent awaits sequentially when they could run in parallel wastes time; use Promise.all for independent work.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Predict

    In what order do these three lines print?

    Read the code, then choose the best answer. The reference explanation stays hidden until you respond.
    stimulus.javascript
    console.log('sync');
    setTimeout(() => console.log('timer'), 0);
    Promise.resolve().then(() => console.log('microtask'));
    Choose the best answer
  2. Exercise 2Explain

    Explain the three states of a promise and what makes a promise settle.

    starter.javascript
    const p = new Promise((resolve) => setTimeout(() => resolve(1), 10));

    Reveal the reference answer
    reference.javascript
    A promise is pending until it settles. It settles by being fulfilled with a value or rejected with a reason, and it can settle only once. Here the executor schedules a timer that calls resolve after 10 milliseconds, moving the promise from pending to fulfilled with the value 1. Later calls to resolve or reject are ignored.

    Authored expected output: 1

    Settling is one-way and one-time. Understanding this prevents bugs where code assumes a promise can be reset or rejected after fulfillment.

  3. Exercise 3Implement

    Implement `delay(ms)` that returns a promise resolving after ms milliseconds. Running `delay(10).then(() => console.log('done'));` should print `done`.

    starter.javascript
    function delay(ms) {
      // your code here
    }

    Reveal the reference answer
    reference.javascript
    function delay(ms) {
      return new Promise((resolve) => setTimeout(resolve, ms));
    }

    Authored expected output: done

    The promise executor schedules a timer whose callback is resolve. When the timer fires, the promise fulfills and any then callbacks are queued as microtasks.

  4. Exercise 4Debug

    This function is supposed to return the fetched value but returns a promise. Fix it.

    starter.javascript
    async function getValue() {
      const value = Promise.resolve(42);
      return value;
    }
    getValue().then((v) => console.log(v));

    Reveal the reference answer
    reference.javascript
    async function getValue() {
      const value = await Promise.resolve(42);
      return value;
    }
    getValue().then((v) => console.log(v));

    Authored expected output: 42

    Without await, value is the promise itself. The async function then resolves with that promise, which the engine unwraps, so the bug is subtle. Adding await reads the fulfilled value directly.

  5. Exercise 5Test

    Write a test that proves two independent async tasks run in parallel rather than in series.

    starter.javascript
    function delay(ms, label) {
      return new Promise((resolve) => setTimeout(() => resolve(label), ms));
    }

    Reveal the reference answer
    reference.javascript
    async function run() {
      const start = Date.now();
      const results = await Promise.all([delay(50, 'a'), delay(50, 'b')]);
      const elapsed = Date.now() - start;
      if (results.join('') !== 'ab') throw new Error('wrong results');
      if (elapsed > 90) throw new Error('not parallel: ' + elapsed + 'ms');
      console.log('tasks ran in parallel');
    }
    run();

    Authored expected output: tasks ran in parallel

    Promise.all starts both delays before awaiting, so the total time is about one delay, not two. Sequentially awaiting each delay would take about 100 milliseconds and fail the timing assertion.

  6. Exercise 6Interview

    Explain the event loop, microtasks and macrotasks, and why an infinite microtask loop can starve timers.

    starter.javascript
    Promise.resolve().then(function loop() {
      Promise.resolve().then(loop);
    });

    Reveal the reference answer
    reference.javascript
    The event loop runs one macrotask, then drains the entire microtask queue, then repeats. Promise callbacks are microtasks, so a microtask that schedules another microtask keeps the queue non-empty forever. Because the engine only moves to the next macrotask after the microtask queue is empty, timers and I/O callbacks never run. This is why unbounded microtask recursion can freeze a page.

    The key insight is the drain-before-next-macrotask rule. A strong answer connects it to a real symptom such as an unresponsive page.

Common misconceptions

#
  • setTimeout with a delay of 0 runs before promise microtasks.
  • await blocks the whole thread.
  • async functions automatically catch their own rejections.

Follow-up practice

#
  • javascript-foundations-errors-and-debugging
  • javascript-foundations-metaprogramming

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.