Skip to main content
eLearner.app
Module 7 · Lesson 1 of 425/32 in the course~12 min
Module lessons (1/4)

Promises: what they are

A Promise is a value that represents the result of an operation that will finish in the future. It can be in one of three states:

  • pending — the operation is still in progress
  • fulfilled — it finished successfully, there is a value
  • rejected — it failed, there is an error

Once it leaves the pending state, it is "settled" forever.

Creating a resolved Promise

The two most common ways — you will almost never create a Promise "by hand" with the constructor:

JS
const p1 = Promise.resolve(42);
const p2 = Promise.reject(new Error('oops'));

Reading the result: .then / .catch

JS
Promise.resolve(10).then((v) => {
  console.log(v); // 10
});

Promise.reject(new Error('no')).catch((e) => {
  console.log(e.message); // 'no'
});

.then receives a function that is called with the resolved value. .catch receives a function called with the error in case of rejection.

Chaining

Every .then returns in turn a Promise: you can chain them to transform the value step by step.

JS
Promise.resolve(5)
  .then((n) => n * 2)
  .then((n) => n + 1)
  .then((n) => console.log(n)); // 11

If any of the .then throws (or returns a Promise that fails), execution jumps to the first subsequent .catch.

Constructor (rare)

JS
const p = new Promise((resolve, reject) => {
  if (Math.random() > 0.5) resolve('ok');
  else reject(new Error('no'));
});

You will use it only when you need to "promisify" something that uses callbacks (e.g. old DOM APIs or setTimeout).

Try it

Exercise#js.m7.l1.e1
Attempts: 0Loading…

Define `promisedVersion(n)` that, given a number, returns a Promise resolved with double of n.

Loading editor…
Show hint

return Promise.resolve(n * 2)

Solution available after 3 attempts

Review exercise

Exercise#js.m7.l1.e2
Attempts: 0Loading…

Define `incrementThree(p)` that receives a Promise of a number and returns a Promise of the number + 3. Use a .then chain.

Loading editor…
Show hint

p.then((n) => n + 3)

Solution available after 3 attempts