Skip to content
JS-03Intermediate6 min read

Asynchronous JavaScript

The event loop, microtasks and macrotasks, promises and async functions, explained with code you can run.

Updated

JavaScript runs your code on a single thread, yet it handles network requests, timers and user input without freezing. The trick is the event loop: slow work happens outside your code, and its results wait in a queue until the thread is free to handle them.

The call stack

When a function is called, it is pushed onto the call stack. When it returns, it is popped off. JavaScript only ever executes what is on top of the stack, so a function that runs for a long time blocks everything else, including rendering, scrolling and clicks.

The event loop

Asynchronous APIs such as setTimeout, fetch and event listeners hand their work to the browser or to Node.js. When that work finishes, a callback is queued. The event loop moves queued callbacks onto the stack whenever the stack is empty, one turn at a time.

  1. Step 1: Run one task

    Execute synchronous code until the call stack is empty. A task is a script, a timer callback or an event handler.

  2. Step 2: Drain the microtask queue

    Run every queued microtask: promise callbacks, await continuations and queueMicrotask. Microtasks added during this step run too, before anything else.

  3. Step 3: Render if it is time

    In browsers, recalculate styles and layout and paint the screen, usually once per frame.

  4. Step 4: Pick the next task

    Take the next callback from the task queue, such as a timer that has expired, and start again.

SourceWhere the callback waits
setTimeout, setIntervalTask queue
DOM events, MessageChannelTask queue
Promise.then, catch, finallyMicrotask queue
Code after awaitMicrotask queue
queueMicrotaskMicrotask queue
requestAnimationFrameRuns right before the next paint

Predict the order

This is the classic exercise. Read the code, write down the order you expect the eight messages to appear in, then run it.

event-loop.js

Press Control or Command with Enter to run the code. Tab inserts spaces; press Escape and then Tab to leave the editor.

Console

Run the code to see its output here.

Synchronous code runs first, then every microtask in the order it was queued, and only then the timer. The code after await is a microtask too, which is why it beats the timeout.

Promises

A promise stands for a value that will exist later. It starts out pending and settles exactly once, either fulfilled with a value or rejected with a reason. Every call to then returns a new promise, which is what makes chaining possible.

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

wait(500)
  .then(() => fetch('/api/lessons'))
  .then((response) => response.json())
  .then((lessons) => console.log(lessons.length))
  .catch((error) => console.error('Something failed:', error))

async and await

An async function always returns a promise. Inside it, await pauses the function until a promise settles and resumes with its value, while the rest of the program keeps running. The same idea exists in many languages.

async function loadProfile(id) {
  const response = await fetch(`/api/users/${id}`)
  if (!response.ok) throw new Error(`Request failed: ${response.status}`)
  return response.json()
}

Running work in parallel

Awaiting inside a loop runs the requests one after another. When requests do not depend on each other, start them all at once and wait for them together with one of the promise combinators.

MethodFulfills whenRejects when
Promise.allevery promise fulfillsany promise rejects
Promise.allSettledevery promise settlesnever
Promise.racethe first promise fulfillsthe first promise rejects
Promise.anythe first promise fulfillsevery promise rejects
parallel.js

Press Control or Command with Enter to run the code. Tab inserts spaces; press Escape and then Tab to leave the editor.

Console

Run the code to see its output here.

Top level await works in every playground. The parallel version finishes in about half the time.

Handling errors

A rejected promise that nobody handles becomes an unhandled rejection. In async functions you use try and catch exactly like synchronous code. Handle errors at the boundary where you can do something useful about them, such as showing a message or retrying.

save-draft.js
async function saveDraft(draft) {
  try {
    const response = await fetch('/api/drafts', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(draft)
    })

    if (!response.ok) throw new Error(`Save failed with status ${response.status}`)
    return await response.json()
  } catch (error) {
    showToast('Your draft could not be saved. Try again in a moment.')
    throw error
  }
}

Summary

  • JavaScript runs one task at a time; the event loop schedules the next one.
  • After every task, all microtasks run before any timer or event.
  • await pauses a function, not the program.
  • Start independent requests together and combine them with Promise.all.
  • Check response.ok: HTTP errors do not reject.

Finished this lesson?

Mark it complete to track your progress across every track in the curriculum.