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:
const p1 = Promise.resolve(42);
const p2 = Promise.reject(new Error('oops'));Reading the result: .then / .catch
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.
Promise.resolve(5)
.then((n) => n * 2)
.then((n) => n + 1)
.then((n) => console.log(n)); // 11If any of the .then throws (or returns a Promise that fails), execution
jumps to the first subsequent .catch.
Constructor (rare)
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
Define `promisedVersion(n)` that, given a number, returns a Promise resolved with double of n.
Show hint
return Promise.resolve(n * 2)
Solution available after 3 attempts
Review exercise
Define `incrementThree(p)` that receives a Promise of a number and returns a Promise of the number + 3. Use a .then chain.
Show hint
p.then((n) => n + 3)
Solution available after 3 attempts