These are the notes for JavaScript episode 26. Callbacks (episode 25) let slow work hand a result back to us, but they left two problems: the pyramid of doom (callbacks nested inside callbacks) and trust: once you hand your function to someone else's code, they decide when, and how many times, to call it. You'll watch a buggy payment library call our callback twice and charge a customer ₹200 instead of ₹100, see why (inversion of control), and then invent the fix: the promise, an object that stands for a value that will arrive later and can be settled only once. You'll read its result with .then, its error with .catch, clean up with .finally, see an unhandled rejection crash Node, use the promise version of fs, flatten the pyramid with chaining, fall into the missing return trap, and run independent jobs together with Promise.all and Promise.allSettled. Every output below is real Node.js output (node main.js); timings in milliseconds will differ slightly on your machine.
Builds on: functions and arrow functions (episode 9), try/catch and Error (13), Date.now() (20), destructuring (an array unpacked into names), the event loop and microtasks (24), callbacks and fs.readFile (25). Leads to: async/await (27).
The real-life idea: the food court token
At a mall food court you order a dosa and pay. The counter doesn't take your phone number and promise to call you. It gives you something right away: a token, number 42, that buzzes.
- Right now the token is waiting: the dosa isn't ready. You hold the token, and you decide what to do with your time.
- Then it buzzes: ready. You collect your dosa.
- Or the counter says sorry, sold out, and tells you why.
- Either way, a token is used once. It can't buzz "ready", buzz again, and charge you twice.
| Food court | JavaScript |
|---|---|
| The token you get straight away | a promise object returned by a slow function |
| Token waiting, dosa not ready | state pending |
| It buzzes: collect your dosa | state fulfilled, with a value (resolve(value)) |
| "Sorry, sold out", with the reason | state rejected, with an error (reject(error)) |
| A token is used only once | a promise settles once; later resolve/reject calls are ignored |
| What you'll do when it buzzes | .then(fn) |
| What you'll do if it's sold out | .catch(fn) |
| Hand the token back either way | .finally(fn) |
The problem: a callback called twice
A callback is a function you hand to other code so it can call you back later. Here a payment function from "some library" takes an amount and a callback, and it has a bug: it calls our callback twice.
function payment(amount, cb) {
cb(null, "paid " + amount);
cb(null, "paid " + amount); // a bug in the library
}
let charged = 0;
payment(100, (err, msg) => {
charged += 100;
console.log(msg, "| total charged:", charged);
});
paid 100 | total charged: 100
paid 100 | total charged: 200
One payment of ₹100, and the customer was charged ₹200. (err, msg) is the error-first callback style from episode 25: the first argument is an error (or null), the second the result.
Why it happened: we handed our function to someone else's code, and they control when and how many times it runs: once, twice, or never. This is called inversion of control. We want the opposite: the slow function should give something back to us, and we stay in charge.
The fix: a promise
A promise is an object that stands for a value that will arrive later: the food court token. It is always in one of three states:
| State | Meaning | How it gets there |
|---|---|---|
| pending | not ready yet | the starting state |
| fulfilled | ready, with a value | resolve(value) |
| rejected | failed, with a reason (usually an Error) |
reject(error) |
A promise that is no longer pending (fulfilled or rejected) is called settled.
You create one with new Promise(executor). The executor is the function you pass in; JavaScript runs it immediately and gives it two functions:
resolve(value): "it's ready, here is the value".reject(error): "it failed, here is why".
A promise settles only once
const token = new Promise((resolve, reject) => {
resolve("paid 100");
resolve("paid 100 again");
reject(new Error("too late"));
});
token.then((msg) => console.log(msg));
console.log(token);
Promise { 'paid 100' }
paid 100
- The first
resolvewins. The secondresolveand therejectare silently ignored: no error, nothing happens. That is the double-charge fix, built into the language. console.log(token)shows the promise is already fulfilled with'paid 100', yet it printed before the.thenmessage. A.thenfunction never runs straight away, even for a settled promise: it is queued as a microtask (the VIP queue from episode 24) and runs after the current code finishes.
A real slow job: pending, then fulfilled
function makeTea(kind) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (kind === "coffee") reject(new Error("We only sell chai"));
else resolve(kind + " chai");
}, 500);
});
}
const p = makeTea("masala");
console.log(p);
p.then((tea) => {
console.log("got", tea);
console.log(p);
});
Promise { <pending> }
got masala chai
Promise { 'masala chai' }
makeTea returns the promise at once (<pending>: the tea is boiling). 500 ms later resolve runs, the promise becomes fulfilled, and the .then function receives the value. We got something back immediately and stayed in control: we decide what to do with the token.
then, catch and finally
| Method | Runs when | Receives |
|---|---|---|
.then(fn) |
the promise is fulfilled | the value |
.catch(fn) |
the promise is rejected | the error |
.finally(fn) |
either way, at the end | nothing (it's for clean-up) |
function makeTea(kind) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (kind === "coffee") reject(new Error("We only sell chai"));
else resolve(kind + " chai");
}, 500);
});
}
makeTea("coffee")
.then((tea) => console.log("got", tea))
.catch((err) => console.log("Sorry:", err.message))
.finally(() => console.log("Token closed"));
Sorry: We only sell chai
Token closed
The .then was skipped because the promise was rejected; .catch got the Error object (its .message is the text), and .finally ran last.
No catch: an unhandled rejection crashes Node
Same makeTea function (every example keeps it at the top, so each file runs on its own). Now the coffee order has no .catch:
function makeTea(kind) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (kind === "coffee") reject(new Error("We only sell chai"));
else resolve(kind + " chai");
}, 500);
});
}
makeTea("coffee").then((tea) => console.log("got", tea));
if (kind === "coffee") reject(new Error("We only sell chai"));
^
Error: We only sell chai
at Timeout._onTimeout (.../main.js:4:37)
Node.js v22.23.4
A rejected promise that nobody catches is an unhandled rejection. Since Node.js 15, it stops the whole program with exit code 1. (Browsers print Uncaught (in promise) Error: ... in the console instead.) Every promise chain needs a .catch at the end.
Node's built-in promises: fs/promises
Node's own functions come in promise versions. require("fs/promises") gives a readFile that returns a promise instead of taking an error-first callback:
const fs = require("fs/promises");
fs.readFile("menu.txt", "utf8")
.then((data) => console.log(data))
.catch((err) => console.log("Error code:", err.code));
Error code: ENOENT
menu.txt doesn't exist. ENOENT ("Error NO ENTry") is the operating system's code for "no such file or directory". Same error as with the callback version, but now it arrives in .catch. Create a menu.txt next to main.js and the file's text is printed instead.
Chaining: from a pyramid to a chain
The trick that makes promises special: .then itself returns a new promise. And if the function inside .then returns a promise, that new promise waits for it before the next .then runs. So steps line up one after another, all at the same level, and one .catch at the end handles a failure in any step.
| Delivery | Promises |
|---|---|
| Each step gives a token | each step returns a promise: step(name, ms) |
| When one buzzes, start the next | .then(() => nextStep()) returns the next promise |
| One complaints desk for any step | one .catch at the end |
function step(name, ms) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (name === "burn it") return reject(new Error("the biryani burned"));
console.log("done:", name);
resolve(name);
}, ms);
});
}
step("take order", 300)
.then(() => step("cook biryani", 500))
.then(() => step("pack it", 200))
.then(() => step("deliver", 400))
.then(() => console.log("Enjoy your meal!"))
.catch((err) => console.log("Problem:", err.message));
done: take order
done: cook biryani
done: pack it
done: deliver
Enjoy your meal!
The right order, and the code is flat, top to bottom, like a recipe. No pyramid. (return reject(...) stops the timer function there, so "done" isn't printed for a failed step.)
A failing step skips to the catch
Replace "cook biryani" with "burn it" (the rest of the file is the same):
function step(name, ms) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (name === "burn it") return reject(new Error("the biryani burned"));
console.log("done:", name);
resolve(name);
}, ms);
});
}
step("take order", 300)
.then(() => step("burn it", 500))
.then(() => step("pack it", 200))
.then(() => step("deliver", 400))
.then(() => console.log("Enjoy your meal!"))
.catch((err) => console.log("Problem:", err.message));
done: take order
Problem: the biryani burned
A rejection jumps straight down to the nearest .catch; every .then in between is skipped. One .catch covered every step.
Why then returns a new promise: values flow down the chain
Whatever a .then function returns becomes the value of the promise that .then returned: a plain value passes straight on, a promise is waited for first. And a .catch that returns normally recovers: the chain carries on.
Promise.resolve(42).then((n) => {
console.log("got", n);
return n * 2;
})
.then((n) => {
console.log("then got", n);
return Promise.resolve(n + 1);
})
.then((n) => console.log("and finally", n));
const first = Promise.resolve("chai");
const second = first.then((t) => t.toUpperCase());
console.log(first === second);
false
got 42
then got 84
and finally 85
first === second is false: .then gave back a brand-new promise, not the same one. (false printed first because .then functions are microtasks.)
Promise.reject(new Error("closed today"))
.catch((err) => {
console.log("caught:", err.message);
return "go to the next stall";
})
.then((plan) => console.log("plan:", plan));
caught: closed today
plan: go to the next stall
Shortcuts: Promise.resolve(value) makes an already-fulfilled promise; Promise.reject(error) makes an already-rejected one. Handy for tests and for starting a chain.
The missing return trap
The .then below uses curly braces and calls step("cook biryani", 500), but doesn't return it:
function step(name, ms) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (name === "burn it") return reject(new Error("the biryani burned"));
console.log("done:", name);
resolve(name);
}, ms);
});
}
step("take order", 300)
.then(() => { step("cook biryani", 500); })
.then((x) => console.log("packing, got:", x));
done: take order
packing, got: undefined
done: cook biryani
Packed before cooking! Without return, the function returns undefined, .then doesn't know about the new promise, and the chain moves on at once with undefined. The cooking promise is "floating": nobody waits for it, and if it rejected, no .catch would see it.
Fix: .then(() => { return step("cook biryani", 500); }), or an arrow function without curly braces, which returns automatically: .then(() => step("cook biryani", 500)).
Promise.all and Promise.allSettled: do things at the same time
Chaining is for steps that depend on each other. Chai and a samosa don't: one cook boils chai while another fries the samosa.
Promise.all([p1, p2, ...])returns one promise that fulfills when all of them are fulfilled, with an array of their values in the same order. If any one rejects, it rejects straight away with that error (fail fast).Promise.allSettled([...])waits for every promise and reports each result as{ status: "fulfilled", value }or{ status: "rejected", reason }. It never rejects.
function makeTea(kind) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (kind === "coffee") reject(new Error("We only sell chai"));
else resolve(kind + " chai");
}, 500);
});
}
function fry(item, ms) {
return new Promise((resolve) => setTimeout(() => resolve(item), ms));
}
const start = Date.now();
Promise.all([makeTea("ginger"), fry("samosa", 1000)])
.then(([tea, snack]) => {
console.log("Ready:", tea, "+", snack);
console.log("took", Date.now() - start, "ms");
});
Ready: ginger chai + samosa
took 1003 ms
About 1000 ms, not 1500: both jobs ran at the same time, so we only waited for the slower one. ([tea, snack]) destructures the array of results into two names.
function makeTea(kind) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (kind === "coffee") reject(new Error("We only sell chai"));
else resolve(kind + " chai");
}, 500);
});
}
Promise.all([makeTea("ginger"), makeTea("coffee")])
.then((both) => console.log("all:", both))
.catch((err) => console.log("all failed:", err.message));
Promise.allSettled([makeTea("ginger"), makeTea("coffee")])
.then((res) => res.forEach((r) => console.log(r.status, r.value || r.reason.message)));
all failed: We only sell chai
fulfilled ginger chai
rejected We only sell chai
One failure and Promise.all gave up on everything; allSettled reported both.
Extras: Promise.race and Promise.any
Promise.race([...])settles like the first promise to settle, whether it fulfills or rejects.Promise.any([...])fulfills with the first success, ignoring failures; only if all reject does it reject, with anAggregateError(an error holding a list of errors in.errors).
function cook(item, ms, fail) {
return new Promise((resolve, reject) =>
setTimeout(() => (fail ? reject(new Error(item + " failed")) : resolve(item)), ms));
}
Promise.race([cook("chai", 500), cook("samosa", 1000)])
.then((first) => console.log("race winner:", first));
Promise.race([cook("chai", 500, true), cook("samosa", 1000)])
.catch((err) => console.log("race lost:", err.message));
Promise.any([cook("chai", 500, true), cook("samosa", 1000)])
.then((first) => console.log("any: first success:", first));
Promise.any([cook("chai", 500, true), cook("samosa", 1000, true)])
.catch((err) => console.log("any:", err.constructor.name, "-", err.errors.length, "errors"));
race winner: chai
race lost: chai failed
any: first success: samosa
any: AggregateError - 2 errors
| Method | Fulfills when | Rejects when |
|---|---|---|
Promise.all |
all fulfill (array of values) | the first one rejects |
Promise.allSettled |
all settle (array of {status, ...}) |
never |
Promise.race |
the first to settle fulfills | the first to settle rejects |
Promise.any |
the first one fulfills | all reject (AggregateError) |
Common mistakes (and what really happens)
| You wrote | What happens | Why | Fix |
|---|---|---|---|
| a library calls your callback twice | total charged: 200 |
someone else controls your function | return a promise instead |
makeTea("coffee").then(...) with no catch |
Error: We only sell chai, Node exits |
unhandled rejection | end every chain with .catch |
.then(() => { step(...); }) |
packing, got: undefined, steps out of order |
the promise was not returned | return step(...) or drop the braces |
resolve("a"); resolve("b"); |
the second value is silently ignored | a promise settles once | resolve exactly once |
Promise.all with one failure |
all failed: We only sell chai |
fail fast | Promise.allSettled for every result |
Promise("chai") |
TypeError: Promise constructor cannot be invoked without 'new' |
Promise is a class |
new Promise(...) |
new Promise() |
TypeError: Promise resolver undefined is not a function |
no executor function given | new Promise((resolve, reject) => { ... }) |
console.log(p) expecting the value |
Promise { <pending> } |
the value isn't there yet | read it in .then |
Mini project: the food court counter
Four orders at once; one item isn't on the menu. Every order gets a token immediately, and the bill counts only what was served.
const menu = { chai: 20, samosa: 15, dosa: 60 };
let nextToken = 41;
function placeOrder(item) {
const token = ++nextToken;
console.log(`Token ${token}: ${item} ordered`);
return new Promise((resolve, reject) => {
setTimeout(() => {
if (!(item in menu)) return reject(new Error(`Token ${token}: ${item} is sold out`));
resolve({ token, item, price: menu[item] });
}, 300 + 100 * item.length);
});
}
Promise.allSettled(["chai", "dosa", "pizza", "samosa"].map(placeOrder))
.then((results) => {
let total = 0;
for (const r of results) {
if (r.status === "fulfilled") {
console.log(`Token ${r.value.token}: collect your ${r.value.item} (Rs ${r.value.price})`);
total += r.value.price;
} else {
console.log(r.reason.message, "- refund at the counter");
}
}
console.log("Bill: Rs", total);
})
.catch((err) => console.log("Unexpected:", err.message))
.finally(() => console.log("Food court closed"));
Token 42: chai ordered
Token 43: dosa ordered
Token 44: pizza ordered
Token 45: samosa ordered
Token 42: collect your chai (Rs 20)
Token 43: collect your dosa (Rs 60)
Token 44: pizza is sold out - refund at the counter
Token 45: collect your samosa (Rs 15)
Bill: Rs 95
Food court closed
.map(placeOrder) turns the list of items into a list of promises; item in menu checks whether the object has that key. Try it: swap allSettled for all and see the whole order fail.
Practice
- Write
wait(ms)that returns a promise which fulfills aftermsmilliseconds. - Write
rollDice()that resolves with a number from 1 to 6 but rejects on a 1. Roll it five times. - Chain three steps with
waitand one.catch. - Time three jobs (400, 600 and 800 ms) one after another, then with
Promise.all.
Solutions
1.
function wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
const start = Date.now();
wait(1000).then(() => console.log("waited", Date.now() - start, "ms"));
waited 1001 ms
2.
function rollDice() {
return new Promise((resolve, reject) => {
const n = Math.floor(Math.random() * 6) + 1;
if (n === 1) reject(new Error("rolled a 1, you lose"));
else resolve(n);
});
}
for (let i = 0; i < 5; i++) {
rollDice()
.then((n) => console.log("rolled", n))
.catch((err) => console.log(err.message));
}
One run (random, so yours will differ):
rolled 4
rolled 5
rolled 6
rolled a 1, you lose
rolled a 1, you lose
Notice the losses print last, even if they were rolled earlier: a rejection has to pass through the skipped .then first, which costs one extra microtask turn.
3.
function wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
wait(300)
.then(() => { console.log("boil water"); return wait(300); })
.then(() => { console.log("add tea leaves"); return wait(300); })
.then(() => { console.log("pour into cups"); })
.catch((err) => console.log("Problem:", err.message));
boil water
add tea leaves
pour into cups
4.
function wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
let start = Date.now();
wait(400)
.then(() => wait(600))
.then(() => wait(800))
.then(() => {
console.log("one after another:", Date.now() - start, "ms");
start = Date.now();
return Promise.all([wait(400), wait(600), wait(800)]);
})
.then(() => console.log("Promise.all:", Date.now() - start, "ms"))
.catch((err) => console.log(err.message));
one after another: 1806 ms
Promise.all: 800 ms
One after another adds the times (400 + 600 + 800); Promise.all waits only for the slowest.
Quick quiz
What does it print?
const p = new Promise((resolve, reject) => {
reject(new Error("sold out"));
resolve("dosa");
});
p.then((v) => console.log("got", v))
.catch((e) => console.log("error", e.message));
- A.
error sold out - B.
got dosa - C.
got dosa, thenerror sold out - D. nothing at all
Answer
A. The promise settles once, with the first call: reject. The later resolve is ignored, so .then is skipped and .catch prints error sold out.
Interview questions
- What is a promise? What are its three states, and what does "settled" mean?
- What problem do promises solve that callbacks have? What is inversion of control?
- What happens if you call
resolvetwice, orrejectafterresolve? - Does the executor passed to
new Promiserun synchronously or later? And a.thencallback? - What does
.thenreturn? How does that make chaining work? - What happens to the rest of a chain when one step rejects?
- What happens in Node.js when a rejected promise has no
.catch? - What goes wrong if you forget
returninside a.then? - Difference between
Promise.all,Promise.allSettled,Promise.raceandPromise.any? - When would you chain steps, and when would you use
Promise.all?
Glossary
| Term | Meaning | Example |
|---|---|---|
| Callback | a function you hand to other code to be called later | (err, msg) => {...} |
| Error-first callback | callback style where the first argument is an error or null |
cb(null, "paid 100") |
| Inversion of control | someone else's code decides when and how often your function runs | the double charge |
| Pyramid of doom | callbacks nested inside callbacks, drifting right | episode 25 |
| Promise | an object standing for a value that will arrive later | makeTea("masala") |
| Executor | the function passed to new Promise; runs immediately |
(resolve, reject) => {...} |
resolve(value) |
fulfil the promise with a value | resolve("masala chai") |
reject(error) |
reject the promise with a reason | reject(new Error("...")) |
| Pending | not settled yet | Promise { <pending> } |
| Fulfilled | settled with a value | Promise { 'masala chai' } |
| Rejected | settled with an error | the coffee order |
| Settled | fulfilled or rejected; can't change again | after the first resolve |
.then(fn) |
run fn with the value when fulfilled; returns a new promise |
.then((tea) => ...) |
.catch(fn) |
run fn with the error when rejected |
.catch((err) => ...) |
.finally(fn) |
run fn either way, for clean-up |
"Token closed" |
| Unhandled rejection | a rejected promise nobody catches; crashes Node | no .catch |
| Microtask | a high-priority queued job; .then callbacks are microtasks |
runs after current code |
fs/promises |
Node's file functions that return promises | fs.readFile(...).then(...) |
ENOENT |
"no such file or directory" error code | missing menu.txt |
| Chaining | linking .then calls so steps run one after another |
order → cook → pack |
| Floating promise | a promise nobody returns or waits for | the missing return |
Promise.resolve / Promise.reject |
make an already-fulfilled / already-rejected promise | Promise.resolve(42) |
Promise.all |
wait for all; fail fast on the first rejection | chai + samosa |
| Fail fast | give up as soon as one part fails | all failed: ... |
Promise.allSettled |
wait for all; report each status |
fulfilled / rejected |
Promise.race |
settle like the first to settle | race winner: chai |
Promise.any |
first success; AggregateError if all fail |
any: first success |
AggregateError |
an error holding several errors in .errors |
2 errors |
| Destructuring | unpacking an array or object into names | ([tea, snack]) => ... |
| Exit code | the number a program ends with; 0 = success, 1 = failure | crash gives 1 |
Summary
- Callbacks put someone else in control of your function (inversion of control); a buggy library can call it twice.
- A promise is a token for a future value: pending, then fulfilled (
resolve) or rejected (reject), and it settles only once. .thengets the value,.catchthe error,.finallyruns either way. A rejection with no.catchcrashes Node..thenreturns a new promise, so steps chain flat; a failing step skips to the nearest.catch. Always return the next promise inside.then.Promise.allruns independent jobs together and fails fast;Promise.allSettledreports every result;raceandanytake the first.
Next episode: async/await. Chains are flat, but still full of .then and arrow functions. What if async code could read exactly like normal code, top to bottom?