Skip to content

Promises

The Course
•
17 min study

Why waiting needs a different shape

Some work finishes later: a network request, a file read, a timer. A browser page has one main thread for your JavaScript. If a function simply waits by looping until the answer arrives, that thread can do nothing else: clicks, typing and redraws queue up behind it. Asynchronous code starts the slow work, returns at once, and arranges for a callback to run when the result is ready.

The program below compares the two. blockingLookup busy-waits for 200 ms. lookup starts a 200 ms timer and immediately returns a promise of the title. (setTimeout and new Promise get a full lesson later today; here they just stand in for "a slow operation".) In both halves a simulated click is scheduled to run as soon as possible. Predict which happens first in each half.

Blocking versus a promise JavaScript
function blockingLookup(id) {
  const end = Date.now() + 200;
  while (Date.now() < end) {
    // Busy-waiting: nothing else can run until this loop ends.
  }
  return `Book ${id}`;
}

function lookup(id) {
  return new Promise(resolve => {
    setTimeout(() => resolve(`Book ${id}`), 200);
  });
}

const blocked = [];
setTimeout(() => blocked.push("click handled"), 0);
blocked.push(blockingLookup("js"));

const waiting = [];
setTimeout(() => waiting.push("click handled"), 0);
lookup("css").then(title => {
  waiting.push(title);
  console.log("Blocking:", blocked.join(" -> "));
  console.log("Promise: ", waiting.join(" -> "));
});
Check your prediction
Text
Blocking: Book js -> click handled
Promise:  click handled -> Book css

The click was due at once in both halves. During blockingLookup it had to wait the full 200 ms, because the loop never let anything else run. During lookup the thread was free, so the click ran first and the title arrived afterwards. A promise is how the second style hands back a result that does not exist yet.

A promise represents an eventual outcome

A Promise is an object representing a value that may be available later. It starts pending, then settles once: fulfilled with a value or rejected with a reason. Settling does not mean the result is automatically printed or stored where you wanted it. Code must handle the outcome.

Real promises come from operations like lookup. To study the rules without waiting, the next examples use Promise.resolve(value), which makes an already-fulfilled promise. .then(onSuccess) registers a callback and returns a new promise. The callback's return becomes the next promise's fulfillment value. .catch(onFailure) handles a rejection; returning an ordinary value from catch recovers the chain. Throwing keeps it rejected.

A then callback runs after the current synchronous work, even for an already-fulfilled promise. Do not read the result immediately after registering a callback and assume it has arrived. Trace what executes now versus what is scheduled for later.

The first examples observe completion using then and catch callbacks. These introductory editors wait for the promise produced by the final chain, so keep that chain as the last statement. The next lesson introduces a main entry point to make this ownership easier to see. Keep the last step as part of the chain, rather than starting unrelated work and assuming the value is ready. In the next lesson, async and await give another way to express those steps.

Predict and trace

Write the output before running. Follow the values through each call; if your prediction differs, identify the first step that surprised you.

Predict, then run JavaScript
const chain = Promise.resolve(20).then(value => value + 5);

console.log("Registered");
chain.then(value => {
  console.log(value);
  console.log("Finished");
});
Check your prediction
Text
Registered
25
Finished

The chain is built first. Registered prints before the scheduled callbacks. Finished is inside the success callback, so it follows the value.

Recover or propagate?

A catch callback that returns text recovers to a fulfilled promise. A later then can use that text. Contrast this with throwing from catch, which keeps the chain rejected. Predict which callbacks run before trying the code.

Recover or propagate? JavaScript
const recovered = Promise.resolve("Notes")
  .then(() => {
    throw new Error("Unavailable");
  })
  .then(() => "This is skipped")
  .catch(error => `Fallback: ${error.message}`);

recovered.then(value => {
  console.log(value);
});
Check your prediction
Text
Fallback: Unavailable

The error skips the next success callback. The final catch supplies a documented fallback value. A fallback should be intentional rather than an empty value that disguises failure.

Trace the contract before building

A then callback must return the next value or promise if the following stage should receive or wait for it. A block that calculates a value and falls off its end fulfills with undefined. A catch can either return a recovery value or throw to keep failure observable.

Trace three columns: current promise outcome, callback invoked and next outcome. Keep fulfillment and rejection paths separate. Awaiting a helper cannot observe a promise that helper discarded. Treat returned promises as part of the API contract, including what normal completion and expected rejection mean.

Build it yourself

Exercise

Promises: practice

Build a chain starting from Promise.resolve(" Notes "). Trim the text, convert it to uppercase, and print it in the final then callback.

Your working space JavaScript
// Each then callback should return the next value.
Hint 1: the idea

A missing return changes the next value to undefined.

Hint 2: a first step

Return trim’s result from one callback and uppercase from the next.

Show one solution
JavaScript
Promise.resolve("  Notes  ")
  .then(text => text.trim())
  .then(text => text.toUpperCase())
  .then(text => {
    console.log(text);
  });
Text
NOTES

Temporarily use a block body without return in the first transformation. Observe the failure, then restore it. The next callback cannot uppercase undefined.

Test a changed requirement

Temporarily use a block body without return in the first transformation. Observe the failure, then restore it. The next callback cannot uppercase undefined.

Explain before moving on

What does then return? Why does an already-fulfilled promise still not run its callback inline?

Going further

Read MDN’s guide to using promises after working through the examples. Use it as a reference when you meet an unfamiliar option; finishing every reference section is not required for this course.

Was this article helpful?

Your response is saved on this device.