Callbacks to promises
| Nested callbacks hurt | |
| The Promise object | |
| Chain with then | |
| Errors skip ahead |
Nested callbacks hurt
Nested callbacks grow to the right and hide the main path. Each step waits inside the previous step, so the reading order is hard to follow. Background on promises in JavaScript shows where this pattern came from.
setTimeout(() => {
console.log("user");
setTimeout(() => {
console.log("orders");
}, 100);
}, 100);
The Promise object
A promise is an object that stands for a value that will arrive later. It starts pending and later becomes fulfilled or rejected. Code below creates one that fulfills after a short timer.
const p: Promise<string> = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Ada");
}, 100);
});
Chain with then
Call then to run a step after the promise fulfills. Return a plain value to pass it down the chain. The chain reads from top to bottom instead of inward.
const q: Promise<string> = Promise.resolve("Ada");
q.then((name) => {
console.log(name);
return name.length;
}).then((len) => {
console.log(len);
});
Errors skip ahead
A throw inside then jumps straight to the next catch. One catch at the end can handle any step above it. This beats passing an error argument through every callback.
Promise.resolve("Ada")
.then(() => {
throw new Error("boom");
})
.catch((err: unknown) => {
console.log(err);
});
Next: Promises
Article author: Arthur Isaev