These are the notes for JavaScript episode 27. Promises (episode 26) fixed callback hell, but a .then chain still doesn't read like normal code, and it has a hidden weakness: every step only sees the value from the step before. A restaurant bill that needs both the customer and the order crashes with ReferenceError: customer is not defined, and the old fix (nesting) brings the pyramid of doom back. So you'll invent async/await: write asynchronous code top to bottom, like a recipe card, where await pauses only this function while the rest of the program keeps running. You'll see that an async function always returns a promise, that await outside an async function is a SyntaxError, that plain try/catch/finally works again, and the three traps that bite everyone: the missing await (Promise { <pending> }, [object Promise]), awaiting independent jobs one by one (slow) instead of with await Promise.all, and await inside forEach (it doesn't wait). Every output below is real Node.js output (node main.js, Node 22); timings in milliseconds will differ slightly on your machine.
Builds on: functions and arrow functions (episode 9), scope and closures (10), try/catch/finally (13), modules (18), the event loop (24), callbacks (25), promises and Promise.all (26). Leads to: error handling in async code (28).
The real-life idea: the recipe card
A chaiwala makes masala chai from a recipe card: boil water, add tea leaves, add milk. The steps are read top to bottom, and each step can use what the earlier steps made.
- One line says "wait until it boils". This recipe pauses right there.
- But the chaiwala doesn't freeze: while this recipe waits, he serves other customers.
- When it boils, he comes back to the same card, at the very next line, with everything from before still in the pot.
| Recipe card | JavaScript |
|---|---|
| A recipe that has "wait" steps | an async function |
| "Wait until it boils" | await somePromise |
| The water boiling on the stove | a promise that is still pending (Node.js does the waiting) |
| Serving other customers meanwhile | the event loop running other code |
| Back to the next line, pot still there | the function resumes with all its variables in scope |
| The boiled water you use next | the value await gives you |
The problem: a .then chain forgets earlier values
A restaurant app has three slow functions that return promises (a promise is an object that stands for a value that will be ready later: it is pending, then fulfilled with a value or rejected with an error). wait(ms) is a promise that fulfils after ms milliseconds. makeBill needs both the customer's name and the order:
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const getCustomer = () => wait(200).then(() => "Asha");
const getOrder = (name) => wait(300).then(() => name + "'s thali");
const makeBill = (name, order) => wait(100).then(() => `${name}: ${order}, Rs 180`);
getCustomer()
.then((customer) => getOrder(customer))
.then((order) => makeBill(customer, order))
.then((bill) => console.log("Bill:", bill))
.catch((err) => console.log(err.name + ":", err.message));
ReferenceError: customer is not defined
Why? Every .then callback is a separate function with its own scope (scope = the region of code where a variable exists). customer only exists inside the first arrow function. The second step receives only order, so by the third step customer is gone. Each step sees just the previous value.
The old fix is to nest each step inside the previous one, so the inner functions can still see customer thanks to closures (a function remembers the variables of the place it was written in):
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const getCustomer = () => wait(200).then(() => "Asha");
const getOrder = (name) => wait(300).then(() => name + "'s thali");
const makeBill = (name, order) => wait(100).then(() => `${name}: ${order}, Rs 180`);
getCustomer().then((customer) => {
return getOrder(customer).then((order) => {
return makeBill(customer, order).then((bill) => {
console.log("Bill:", bill);
});
});
});
Bill: Asha: Asha's thali, Rs 180
It works, but the pyramid of doom (code that drifts further right with every step) is back, just with .then instead of callbacks.
The fix: async and await
Two keywords turn a function into a recipe card:
asyncin front of a function marks it as a function that may pause. It always returns a promise (more below).await promise, used inside an async function, pauses the function on that line until the promise settles (fulfils or rejects), then gives you its value like a normal return value.- Only this function pauses. The event loop keeps running everything else. Because everything happens in one function, variables from earlier lines stay in scope.
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const getCustomer = () => wait(200).then(() => "Asha");
const getOrder = (name) => wait(300).then(() => name + "'s thali");
const makeBill = (name, order) => wait(100).then(() => `${name}: ${order}, Rs 180`);
async function serve() {
const customer = await getCustomer();
const order = await getOrder(customer);
const bill = await makeBill(customer, order);
console.log("Bill:", bill);
}
serve();
console.log("Serving the next table...");
Serving the next table...
Bill: Asha: Asha's thali, Rs 180
serve()runs normally until its firstawait, then pauses and hands control back. That's whyServing the next table...prints first.- When each promise fulfils,
serveresumes at the next line.customeris still in scope three lines later: no.then, no nesting. - It is still promises underneath; async/await is a nicer way to write them (this is called syntactic sugar: new syntax for something the language could already do).
await doesn't block the thread
"Pausing" sounds like the frozen chaiwala from episode 24, the busy while loop that stopped everything. Let's check with a ticker every 300 ms while boilTea awaits one second:
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const start = Date.now();
const timer = setInterval(() => console.log("tick", Date.now() - start, "ms"), 300);
async function boilTea() {
console.log("Boiling...");
await wait(1000);
console.log("Tea ready at", Date.now() - start, "ms");
clearInterval(timer);
}
boilTea();
Boiling...
tick 300 ms
tick 601 ms
tick 902 ms
Tea ready at 1019 ms
The ticks kept coming while boilTea was paused. await is not a busy wait (a loop that checks the clock and holds the call stack). The function steps aside, the call stack is free, and the rest of the function is scheduled as a microtask (a high-priority job in the event loop's queue) when the promise is ready. Blocking means holding the only thread so nothing else runs; await never does that.
An async function always returns a promise
async function getTea() {
return "masala chai";
}
const result = getTea();
console.log(result);
result.then((tea) => console.log("then:", tea));
Promise { 'masala chai' }
then: masala chai
getTea() returns Promise { 'masala chai' }, not the string. Whatever you return from an async function becomes the promise's value; whatever you throw becomes its rejection. So the caller uses await (inside another async function) or .then to get the value.
await is only valid in async functions
Forget the async keyword and the file doesn't run at all:
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const getCustomer = () => wait(200).then(() => "Asha");
const getOrder = (name) => wait(300).then(() => name + "'s thali");
const makeBill = (name, order) => wait(100).then(() => `${name}: ${order}, Rs 180`);
function serve() {
const customer = await getCustomer();
console.log(customer);
}
serve();
const customer = await getCustomer();
^^^^^
SyntaxError: await is only valid in async functions and the top level bodies of modules
A SyntaxError is found before any line runs, so nothing is printed. Fix: async function serve().
Top-level await in modules
The message mentions "top level bodies of modules": in an ES module (a file that uses import/export, episode 18), you may use await outside any function, at the top level of the file:
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
console.log("Opening the stall...");
await wait(500);
console.log("Stall open!");
Opening the stall...
Stall open!
Node 22 noticed the top-level await and ran this main.js as an ES module. To be explicit (and for older Node versions), add { "type": "module" } to package.json or name the file main.mjs. In a CommonJS file ("type": "commonjs", the require style) it fails with the same SyntaxError. In the browser it works in <script type="module">.
Errors: try/catch/finally works again
When you await a promise that rejects, await throws the error right on that line, as if it were normal code. So a plain try/catch/finally catches it. Remember episode 25: try/catch couldn't catch an error thrown later inside a timer callback, because the try block had already finished. With await, the function is still waiting on that line, so its catch is still there.
function makeTea(kind) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (kind === "coffee") reject(new Error("We only sell chai"));
else resolve(kind + " chai");
}, 500);
});
}
async function order(kind) {
try {
const tea = await makeTea(kind);
console.log("Enjoy your", tea);
} catch (err) {
console.log("Sorry:", err.message);
} finally {
console.log("Token closed for", kind);
}
}
order("coffee");
Sorry: We only sell chai
Token closed for coffee
try: the code that might fail.catch (err): runs if it fails;erris the rejection reason (here anErrorobject with amessage).finally: runs either way.- Order
"masala"instead and you getEnjoy your masala chaithenToken closed for masala. - Episode 28 goes deep: unhandled rejections, retries, timeouts.
Trap 1: the missing await
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const getCustomer = () => wait(200).then(() => "Asha");
const getOrder = (name) => wait(300).then(() => name + "'s thali");
const makeBill = (name, order) => wait(100).then(() => `${name}: ${order}, Rs 180`);
async function serve() {
const customer = getCustomer();
console.log(customer);
console.log("Bill: " + customer);
}
serve();
Promise { <pending> }
Bill: [object Promise]
No error, no crash, just a wrong bill. Without await, customer holds the promise (the token), not the value (the food). Promise { <pending> } is how Node prints a promise that hasn't settled yet. In a string, an object becomes [object Promise]. If you see [object Promise] or Promise { <pending> }, look for a missing await. The fix is const customer = await getCustomer();, which prints Asha and Bill: Asha.
Trap 2: slow by accident (sequential vs Promise.all)
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 fry = (item, ms) => new Promise((resolve) => setTimeout(() => resolve(item), ms));
async function breakfast() {
let start = Date.now();
const tea = await makeTea("ginger");
const snack = await fry("samosa", 1000);
console.log("one by one:", tea, "+", snack, Date.now() - start, "ms");
start = Date.now();
const [t2, s2] = await Promise.all([makeTea("ginger"), fry("samosa", 1000)]);
console.log("together:", t2, "+", s2, Date.now() - start, "ms");
}
breakfast();
one by one: ginger chai + samosa 1502 ms
together: ginger chai + samosa 1001 ms
- Sequential: each
awaitwaits before the next line even starts the next job: 500 + 1000 ≈ 1500 ms. - Parallel (well, concurrent: both waits overlap): call both functions first, so both jobs start, then
await Promise.all([...]).Promise.alltakes an array of promises and gives back one promise for an array of their values, in the same order. Time ≈ the slowest job, 1000 ms. const [t2, s2] = ...is array destructuring (episode 12): it unpacks the array into two variables.- Rule: if job B needs job A's result (like
getOrder(customer)), await them one by one. If they're independent, useawait Promise.all. If any promise inPromise.allrejects, the wholeawaitthrows that error.
Trap 3: await inside forEach
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const orders = ["chai", "samosa", "dosa"];
orders.forEach(async (item) => {
await wait(300);
console.log("served", item);
});
console.log("all served?");
all served?
served chai
served samosa
served dosa
all served? prints first, before anything was served. forEach doesn't know about promises: it calls the async arrow function for each item (each one starts, hits await, and returns a promise), ignores those promises, and moves on. The fix is a plain for...of loop inside an async function, where await really pauses the loop:
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const orders = ["chai", "samosa", "dosa"];
async function serveAll() {
for (const item of orders) {
await wait(300);
console.log("served", item);
}
console.log("all served!");
}
serveAll();
served chai
served samosa
served dosa
all served!
Use for...of when each item must wait for the previous one. If the items are independent and order of finishing doesn't matter, await Promise.all(orders.map(async (item) => ...)) runs them all at once instead (map collects the promises that forEach throws away).
Extras: async arrow functions and async methods
async works on every kind of function: an async arrow function puts async before the parameters (async (sugar) => ...), and an async method puts it before the method name, in an object or a class (episode 16), with this working as usual:
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const makeChai = async (sugar) => {
await wait(200);
return sugar ? "sweet chai" : "plain chai";
};
const stall = {
name: "Raju Chai",
async open() {
return this.name + " is open";
},
};
class Kitchen {
async cook(dish) {
await wait(100);
return dish + " is ready";
}
}
async function main() {
console.log(await stall.open());
console.log(await makeChai(true));
console.log(await new Kitchen().cook("dosa"));
}
main();
Raju Chai is open
sweet chai
dosa is ready
await can sit inside any expression, like console.log(await stall.open()). stall.open() never awaits, yet it still returns a promise, because it's async.
Common mistakes (and what really happens)
| You wrote | What happens | Why | Fix |
|---|---|---|---|
.then((order) => makeBill(customer, order)) |
ReferenceError: customer is not defined |
each .then callback has its own scope |
async/await keeps every variable in one function |
function f() { await p; } |
SyntaxError: await is only valid in async functions and the top level bodies of modules |
await needs async |
async function f() |
await at the top of a CommonJS file |
the same SyntaxError |
top-level await only works in ES modules | "type": "module" or .mjs, or wrap the code in an async function |
const c = getCustomer(); (no await) |
Promise { <pending> }, Bill: [object Promise] |
you stored the promise, not its value | const c = await getCustomer(); |
await a(); await b(); for independent jobs |
~1500 ms instead of ~1000 ms | each waits before the next starts | await Promise.all([a(), b()]) |
arr.forEach(async (x) => { await ... }) |
all served? prints first |
forEach ignores the returned promises |
for (const x of arr) { await ... } |
Mini project: the restaurant service desk
Three tables. Each table's dishes cook at the same time (Promise.all), the tables are served one after another (for...of), and a dish that's not on the menu is handled by try/catch/finally:
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const MENU = { chai: 20, samosa: 15, dosa: 60 };
async function cook(item) {
await wait(item === "dosa" ? 600 : 300);
if (!(item in MENU)) throw new Error(item + " is not on the menu");
return item;
}
async function serveTable(table, items) {
const start = Date.now();
try {
const dishes = await Promise.all(items.map((item) => cook(item)));
const total = dishes.reduce((sum, dish) => sum + MENU[dish], 0);
console.log(`Table ${table}: ${dishes.join(", ")} | Rs ${total} | ${Date.now() - start} ms`);
} catch (err) {
console.log(`Table ${table}: sorry, ${err.message}`);
} finally {
console.log(`Table ${table}: token closed`);
}
}
async function main() {
const tables = [
[1, ["chai", "samosa"]],
[2, ["dosa", "chai", "chai"]],
[3, ["pizza", "chai"]],
];
for (const [table, items] of tables) {
await serveTable(table, items);
}
console.log("All tables done.");
}
main();
Table 1: chai, samosa | Rs 35 | 302 ms
Table 1: token closed
Table 2: dosa, chai, chai | Rs 100 | 601 ms
Table 2: token closed
Table 3: sorry, pizza is not on the menu
Table 3: token closed
All tables done.
- Table 1 took ~300 ms, not 600: chai and samosa cooked together. Table 2 took ~600 ms (the dosa, the slowest dish), not 1200.
throwinside an async function rejects its promise, soPromise.allrejects and thecatchprints the message.finallycloses every token.item in MENUchecks whether an object has a key;for (const [table, items] of tables)destructures each pair.
Practice
- Rewrite this promise chain with async/await so that the last step can use both the order and the rider:
placeOrder("biryani")→assignRider(order)→deliver(order, rider). - Write
async function getBill()that awaits three steps (get item prices, add 5% GST, round off) and returns the bill; print it from outside. - Write
payOnline(amount)that rejects above Rs 500, and catch the failure withtry/catch/finally. - Time three jobs (300, 500, 700 ms): one by one vs
await Promise.all.
Solutions
1.
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const placeOrder = (item) => wait(200).then(() => ({ id: 7, item }));
const assignRider = (order) => wait(300).then(() => "Ravi");
const deliver = (order, rider) => wait(100).then(() => `Order #${order.id} (${order.item}) delivered by ${rider}`);
async function delivery() {
const order = await placeOrder("biryani");
const rider = await assignRider(order);
const message = await deliver(order, rider);
console.log(message);
}
delivery();
Order #7 (biryani) delivered by Ravi
2.
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const getItems = () => wait(200).then(() => [20, 15, 60]);
const addGst = (subtotal) => wait(100).then(() => subtotal * 1.05);
const roundOff = (amount) => wait(100).then(() => Math.round(amount));
async function getBill() {
const items = await getItems();
const subtotal = items.reduce((sum, price) => sum + price, 0);
const withGst = await addGst(subtotal);
const total = await roundOff(withGst);
return `Subtotal Rs ${subtotal}, total Rs ${total}`;
}
getBill().then((bill) => console.log(bill));
Subtotal Rs 95, total Rs 100
getBill() returns a promise (it's async), so the outside code uses .then. 20 + 15 + 60 = 95, plus 5% = 99.75, rounded to 100.
-
Same shape as the
orderexample:async function payOnline(amount) { await wait(300); if (amount > 500) throw new Error("UPI limit is Rs 500"); return "paid Rs " + amount; }, then call it insidetry { console.log(await payOnline(amount)); } catch (err) { ... } finally { ... }. With 900 you getPayment failed: UPI limit is Rs 500and thefinallyline. -
Same shape as trap 2 with three jobs: one by one ≈ 300 + 500 + 700 = 1500 ms (we got 1504 ms);
await Promise.all([...])≈ the slowest job, 700 ms.
Quick quiz
In what order do these print?
async function f() {
console.log("B");
await null;
console.log("D");
}
console.log("A");
f();
console.log("C");
- A.
A B C D - B.
A B D C - C.
A C B D - D.
B D A C
Answer
A (A B C D). f runs normally until its first await, so B prints right after A. At await (even await null, which isn't a promise; await wraps any value in a fulfilled promise) f pauses, and the main code prints C. Then f resumes as a microtask and prints D.
Interview questions
- What problem does async/await solve compared with
.thenchains? - What does an
asyncfunction return? What if it returns a plain value, or throws? - What exactly does
awaitdo? Does it block the thread? - Where can you use
await? What is top-level await, and where does it work? - How do you handle a rejected promise with async/await?
- Why does
console.log(getUser())printPromise { <pending> }? - Two independent API calls: how do you make them run concurrently with async/await? What if one fails?
- Why doesn't
awaitwork insideforEach? What do you use instead (in order, and all at once)? - Is async/await different from promises underneath? (No: it's syntactic sugar over promises and microtasks.)
- Predict the output: a log, an async function with
await, another log.
Glossary
| Term | Meaning | Example |
|---|---|---|
| Asynchronous | work that finishes later while the program keeps going | a timer, a network request |
| Promise | an object standing for a value that will be ready later | wait(200) |
| Pending / fulfilled / rejected / settled | still waiting / finished with a value / failed with an error / either of the last two | Promise { <pending> } |
.then(fn) |
run fn with the promise's value when it fulfils |
getTea().then(...) |
async function |
a function that may pause at await and always returns a promise |
async function serve() |
await |
pause this async function until the promise settles, then resume with its value (or throw its rejection reason, the error it carries) | await getCustomer() |
| Top-level await | await outside any function, allowed only in ES modules |
await wait(500); |
| ES module / CommonJS | import/export files / require files |
"type": "module" |
SyntaxError |
code JavaScript can't even parse; nothing runs | await in a normal function |
ReferenceError |
using a variable that doesn't exist in this scope | customer is not defined |
| Scope | the region of code where a variable exists | inside one .then callback |
| Closure | a function remembering variables from where it was written | nested .then sees customer |
| Pyramid of doom | code nested deeper and deeper to the right | nested .thens |
| Syntactic sugar | nicer syntax for something already possible | async/await over promises |
| Blocking | holding the only thread so nothing else runs | a busy while loop |
| Busy wait | waiting by looping and checking the clock | while (Date.now() < end) {} |
| Event loop | runs queued callbacks whenever the call stack is empty | ticks during await |
| Call stack | the functions being run right now | serve pauses and leaves it |
| Microtask | a high-priority queued job; promise reactions and resumed awaits |
D in the quiz |
try / catch / finally |
run code / handle its error / always run at the end | catch (err) |
[object Promise] |
what a promise turns into inside a string | the missing-await bill |
| Sequential | one job after another | await a(); await b(); |
| Concurrent (parallel) | jobs whose waiting overlaps | await Promise.all([a(), b()]) |
Promise.all([...]) |
one promise for all values, in order; rejects if any rejects | [t2, s2] |
| Array destructuring | unpack an array into variables | const [t2, s2] = ... |
forEach / for...of |
call a function per item (ignores promises) / a loop that await can pause |
trap 3 |
setInterval / clearInterval |
run a function every ms ms / stop it |
the ticker |
| Async arrow function / async method | async on an arrow function / on an object or class method |
async () => ..., async open() |
Summary
- A
.thenchain forgets earlier values (each callback has its own scope), and nesting brings the pyramid back. asyncmarks a function that may pause; it always returns a promise (returned value = fulfilled, thrown error = rejected).awaitpauses only this function until the promise settles; the event loop keeps running, so it never blocks the thread.awaitis only valid in async functions, or at the top level of an ES module.- A rejected
awaitthrows, so plaintry/catch/finallyhandles async errors. - Traps: a missing
awaitgivesPromise { <pending> }/[object Promise]; independent jobs belong inawait Promise.all;awaitinforEachdoesn't wait, so usefor...of.
Next episode: Error handling in async code. What happens when something fails halfway through a long async job, and how do you retry, add timeouts, and never lose an error?