typestar

What a promise is in JavaScript

A pending value that settles once, and never changes after.

const promise = new Promise((resolve, reject) => {
  console.log("executor runs now");
  setTimeout(() => resolve("settled"), 10);
  setTimeout(() => resolve("ignored"), 20);
});

console.log("after the constructor");

promise.then((value) => console.log("then:", value));

Promise.resolve("already done").then((value) => console.log(value));
Promise.reject(new Error("nope")).catch((error) => console.log(error.message));

How it works

  1. The executor runs immediately, synchronously.
  2. resolve or reject settles it; later calls do nothing.
  3. then always runs asynchronously, after the current task.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
416
Tokens
122
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 77 seconds.

Type this snippet

Step 2 of 5 in Promises, step 2 of 19 in Promises & async.

← Previous Next →