Sub topic 1
Why Promises Exist: The Trouble with Nested Callbacks
Prerequisites
This chapter assumes you know JavaScript functions, closures and arrow functions. You should also be familiar with arrays and objects, callbacks and setTimeout, and running code in a browser console or Node.js.
The Trouble with Nested Callbacks
When each async step needs the previous step's result, callbacks nest inside each other. Every level also has to handle its own errors:
function step(value, cb) {
setTimeout(() => cb(null, value + 1), 50);
}
step(1, (err, a) => {
if (err) return console.error(err);
step(a, (err, b) => {
if (err) return console.error(err);
step(b, (err, c) => {
if (err) return console.error(err);
console.log(c); // 4
});
});
});Callbacks also have no single owner. Nothing stops a careless API from calling your callback twice, or never calling it. A promise fixes this. It is an object that stands for a result that doesn't exist yet, and the result can be set only once.
States and Settlement
A promise is always in one of three states:
- pending: the result is not known yet.
- fulfilled: the promise holds a value.
- rejected: the promise holds a reason, usually an
Error.
A promise that is fulfilled or rejected is called settled. A settled promise never changes state again. Any later calls to resolve or reject are ignored.
Creating Promises with new Promise
The constructor runs your executor function right away. It passes in resolve and reject:
function delay(ms, value) {
return new Promise((resolve) => {
setTimeout(() => resolve(value), ms);
});
}
delay(100, 'done').then((v) => console.log(v)); // logs "done" after about 100 msIf the executor throws, the promise rejects.
Shortcuts: Promise.resolve and Promise.reject
Promise.resolve(x) returns a promise that is already fulfilled with x. If x is already a promise, it returns x itself. Promise.reject(err) returns a promise that is already rejected.
Reacting with then, catch and finally
then(onFulfilled)runs when the promise fulfills.catch(onRejected)runs when it rejects.finally(fn)runs in both cases. It receives no argument.
Promise.reject(new Error('nope'))
.then((v) => console.log('value:', v))
.catch((err) => console.log('error:', err.message)) // error: nope
.finally(() => console.log('done')); // doneExercise
What does this log? new Promise((resolve, reject) => { resolve(1); reject(new Error('x')); resolve(2); }).then(console.log, (e) => console.log('err'))
Show answer
It logs 1. The first resolve(1) settles the promise, and a settled promise never changes state, so the later reject and resolve calls are ignored.