← All teaching notes

JAVASCRIPT

What actually happens when you await?

Promises, pauses, and the code that keeps running.

An asynchronous function does not freeze the whole program. It can pause its own execution while other JavaScript work continues. That distinction is the key to understanding async and await.

A promise represents a future result

A promise is an object representing an operation that may still be pending, may succeed with a value, or may fail with a reason. Calling an async function always returns a promise—even when its return statement contains an ordinary value.

async function getMessage() {
  return "Ready";
}

getMessage().then(message => {
  console.log(message); // Ready
});

then() is a method on a promise. The function you pass into it is a callback that runs after the promise fulfills. It is not the result itself.

Await pauses the current async function

async function showMessage() {
  console.log("A");
  const message = await getMessage();
  console.log(message);
}

showMessage();
console.log("B");
// Output: A, B, Ready

The function prints A, reaches await, and yields. The caller continues and prints B. The continuation of showMessage then prints Ready. Even an already-fulfilled promise resumes after the current synchronous work has finished.

Update the interface after the value arrives

Place the UI update after await, inside the async function. Surround the operation with try/catch to handle failure, and use finally for cleanup that should happen in either case.

async function loadProfile() {
  status.textContent = "Loading…";
  try {
    const response = await fetch("/api/profile");
    if (!response.ok) throw new Error("Request failed");
    const profile = await response.json();
    nameElement.textContent = profile.name;
    status.textContent = "Loaded";
  } catch (error) {
    status.textContent = "Could not load the profile.";
  } finally {
    loadButton.disabled = false;
  }
}

This example assumes the DOM elements already exist and the server implements /api/profile. Notice the explicit response check: fetch does not reject just because the server returns an HTTP error status.

Ask yourself: which lines need the result, and which lines can run while the operation is pending?
← More teaching notesDiscuss this topic ↗