typestar

Promises in JavaScript

Constructing a promise and chaining its outcomes.

function delay(ms, value) {
  return new Promise((resolve, reject) => {
    if (ms < 0) reject(new Error("negative delay"));
    setTimeout(() => resolve(value), ms);
  });
}

delay(100, "done")
  .then((result) => result.toUpperCase())
  .catch((error) => `failed: ${error.message}`)
  .finally(() => console.log("settled"));

How it works

  1. The executor receives resolve and reject.
  2. then transforms the value; catch handles errors.
  3. finally runs either way.

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
308
Tokens
100
Three-star pace
95 tpm

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

Type this snippet

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

Next →