Callbacks to promises
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 JavaScript promises shows where this pattern came from.
setTimeout(() => { console.log("user"); setTimeout(() => { console.log("orders"); }, 100); }, 100);
user
orders
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); }); p.then((name) => console.log(name));
Ada
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); });
Ada
3
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 as Error).message); });
boom
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is a promise?
Answer
An object that stands for a value that arrives later
A promise starts pending and later becomes fulfilled or rejected.
-
What does
thenreturn?Answer
A new promise that continues the chain
The new promise lets the next then wait for this step, which is what makes chaining work.
-
What does a throw inside
thendo?Answer
It skips the remaining then steps and reaches the next catch
The error jumps to the rejection path, so one catch can handle any step above it.
-
Why are deeply nested callbacks hard to read?
Answer
The reading order grows inward instead of top to bottom
Each step hides inside the previous callback, which obscures the main path.
-
What does this program print?
setTimeout(() => { console.log("a"); setTimeout(() => console.log("b"), 10); }, 10);Answer
a / b
The outer timer runs first and schedules the inner one after it.
-
What does this program print?
Promise.resolve("Ada").then((name) => { console.log(name); });Answer
Ada
The resolved value reaches the callback, which logs it.
-
What does this program print?
const q: Promise<string> = Promise.resolve("Ada"); q.then((name) => { console.log(name); return name.length; }).then((len) => { console.log(len); });Answer
Ada / 3
The first step logs the name and returns its length, and the second logs 3.
-
What does this program print?
Promise.resolve("Ada") .then(() => { throw new Error("boom"); }) .catch((err: unknown) => { console.log((err as Error).message); });Answer
boom
The throw skips to catch, and the message of the error is boom.
-
What does the compiler say about this program?
const p: Promise<string> = "Ada"; console.log(p);Answer
error TS2322: Type 'string' is not assignable to type 'Promise<string>'.
A plain string is not a promise, even when the promise would resolve to a string.
-
What does the compiler say about this program?
Promise.resolve("Ada").then((name: number) => { console.log(name); });Answer
error TS2345: Argument of type '(name: number) => void' is not assignable to parameter of type '(value: string) => void | PromiseLike<void>'.
The promise carries a string, so a callback that expects a number does not fit.
Article author: Arthur Isaev