🎓 A1Learner
🔍
0 of 50 lessons completed

Promises

A promise is an object that holds the result of work that finishes later. The result arrives when the work ends.

A promise that finishes later

This promise resolves with Done after a short wait.

const promise = new Promise((resolve) => {
  setTimeout(() => resolve("Done"), 100);
});

Reading the result

This reads the promise from the last snippet. The value arrives as an input.

promise.then((value) => {
  console.log(value);
});

Catching a failure

Catch runs when the promise rejects. The error arrives as an input.

const broken = new Promise((resolve, reject) => {
  setTimeout(() => reject(new Error("Failed")), 100);
});
broken.catch((error) => {
  console.log(error.message);
});

Example

console.log("Start");

const promise = new Promise((resolve) => {
  setTimeout(() => resolve("Done"), 100);
});

promise.then((value) => {
  console.log(value);
});

console.log("End");

Key points

  • A new promise is pending.
  • Pending means the work is still running.
  • A finished promise is fulfilled or rejected.
  • Fulfilled means the work finished with a value.
  • Rejected means the work failed with an error.
  • Call resolve with the result to fulfill the promise.
  • Call reject with an error to reject the promise.
  • The then method runs a function when the promise fulfills.
  • The catch method runs a function when the promise rejects.

In this example, the first print shows Start. The promise resolves with Done after a short wait. The then call waits for that value and prints it. The last print shows End at once. End prints before Done because the program does not wait for the promise.

Note

A promise runs its work once, even with many then calls.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does then do?