In the previous chapter, we replaced nested callbacks with promise chains:
getUser(7)
.then(user => getOrders(user))
.then(orders => console.log(orders))
.catch(error => console.log(error.message));That's much better than callback hell, but it's still a chain of small functions. Wouldn't it be nice to write asynchronous code that reads like normal, top-to-bottom code?
async function showOrders() {
try {
const user = await getUser(7);
const orders = await getOrders(user);
console.log(orders);
} catch (error) {
console.log(error.message);
}
}That's exactly what async and await give us. Added in ES2017, they are now the most common way to write asynchronous JavaScript. They don't replace promises; they're a cleaner syntax for working with promises.
The async Keyword
An
asyncfunction is a function that always returns a promise. Inside it, you can use theawaitkeyword.
Put async before a function to make it asynchronous:
async function greet() {
return "Hello";
}
const result = greet();
console.log(result);
result.then(value => console.log(value));Output:
Promise { 'Hello' }
HelloEven though we returned a plain string, calling greet() gave us a promise fulfilled with "Hello". The rules are simple:
Inside the async function... | The returned promise... |
|---|---|
| Fulfills with |
| Rejects with |
| Follows that promise (fulfills or rejects the same way) |
async function failing() {
throw new Error("Something went wrong");
}
failing().catch(error => console.log("Caught:", error.message));Output:
Caught: Something went wrongAll function styles can be async:
async function declared() {} // function declaration
const expressed = async function () {}; // function expression
const arrow = async () => {}; // arrow function
class Api {
async load() {} // class method
}The await Keyword
awaitpauses the async function until a promise settles, then gives you its fulfilled value (or throws its rejection error).
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function makeChai() {
console.log("Boiling water...");
await delay(1000);
console.log("Adding tea leaves...");
await delay(1000);
console.log("Chai is ready!");
}
makeChai();Output:
Boiling water...
Adding tea leaves...
Chai is ready!Each line appears about one second after the previous one. The code looks synchronous, but it isn't blocking anything, as we'll see next.
await Gives You the Value
Without await, you have a promise. With await, you have the value inside it:
function getScore() {
return new Promise(resolve => setTimeout(() => resolve(95), 500));
}
async function main() {
const withoutAwait = getScore();
const withAwait = await getScore();
console.log(withoutAwait);
console.log(withAwait);
}
main();Output:
Promise { 95 }
95(By the time we log withoutAwait, its timer has also finished, which is why Node shows Promise { 95 } rather than <pending>. It's still a promise object, not the number.)
await Pauses the Function, Not the Program
This is the most important thing to understand. await only pauses the async function it's in. The rest of your program keeps running.
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function task() {
console.log("2: task started");
await delay(1000);
console.log("4: task resumed after 1 second");
}
console.log("1: before calling task");
task();
console.log("3: after calling task");Output:
1: before calling task
2: task started
3: after calling task
4: task resumed after 1 secondHere's what happens:
1. "1: before..." is printed.
2. task() starts running synchronously and prints "2: task started".
3. It hits await. The function is paused, and task() returns a pending
promise to the caller immediately.
4. The main code continues and prints "3: after calling task".
5. After 1 second the promise fulfills. The rest of task() is scheduled
as a microtask and resumes, printing "4: ...".Remember the generators chapter, where a function could pause at yield and resume later? await works on the same idea: the function pauses at await, and the event loop resumes it when the promise is settled.
Rewriting a Promise Chain
Let's convert the example from the promises chapter:
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function getUser(id) {
await delay(300);
return { id, name: "Priya" };
}
async function getOrders(user) {
await delay(300);
return ["Laptop", "Headphones"];
}
async function showDashboard() {
const user = await getUser(7);
console.log("User:", user.name);
const orders = await getOrders(user);
console.log("Orders:", orders.join(", "));
}
showDashboard();Output:
User: Priya
Orders: Laptop, HeadphonesNo .then(), no nesting, and regular variables (user, orders) that stay in scope for the whole function. This is why most modern code uses async/await.
Error Handling with try...catch
When an awaited promise rejects, await throws the error. That means we can use the regular try...catch...finally from the error handling chapter:
function checkSeat(seat) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (seat <= 50) {
resolve(`Seat ${seat} booked`);
} else {
reject(new Error(`Seat ${seat} does not exist`));
}
}, 300);
});
}
async function book(seat) {
try {
const message = await checkSeat(seat);
console.log(message);
} catch (error) {
console.log("Booking failed:", error.message);
} finally {
console.log("Done with seat", seat);
}
}
async function main() {
await book(12);
await book(99);
}
main();Output:
Seat 12 booked
Done with seat 12
Booking failed: Seat 99 does not exist
Done with seat 99Unlike the callback example in the event loop chapter, try...catch does catch async errors here, because await pauses the function inside the try block until the promise settles.
If you don't catch the error inside the async function, its returned promise rejects, so the caller must handle it, either with its own try...catch around await, or with .catch():
async function loadData() {
throw new Error("Network error");
}
loadData().catch(error => console.log("Handled by caller:", error.message));Output:
Handled by caller: Network errorSequential vs Parallel
This is the most common performance mistake with async/await. Look at this code:
function load(name, ms) {
return new Promise(resolve => setTimeout(() => resolve(name), ms));
}
async function sequential() {
const start = Date.now();
const profile = await load("profile", 500);
const settings = await load("settings", 500);
const notifications = await load("notifications", 500);
const seconds = ((Date.now() - start) / 1000).toFixed(1);
console.log(`Sequential took about ${seconds} seconds`);
}
sequential();Output:
Sequential took about 1.5 secondsEach await waits for the previous one to finish, so the total is 0.5 + 0.5 + 0.5 seconds. But these three requests don't depend on each other! We can start all of them first, then wait for them together with Promise.all():
function load(name, ms) {
return new Promise(resolve => setTimeout(() => resolve(name), ms));
}
async function parallel() {
const start = Date.now();
const [profile, settings, notifications] = await Promise.all([
load("profile", 500),
load("settings", 500),
load("notifications", 500)
]);
const seconds = ((Date.now() - start) / 1000).toFixed(1);
console.log(`Parallel took about ${seconds} seconds`);
console.log(profile, settings, notifications);
}
parallel();Output:
Parallel took about 0.5 seconds
profile settings notificationsThree times faster. The rule:
If step B needs the result of step A,
awaitthem one after another. If they're independent, start them together andawait Promise.all([...]).
All the combinators from the previous chapter (Promise.all, allSettled, race, any) work with await, because they return promises.
await in Loops
for...of Works (One at a Time)
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function sendEmails(students) {
for (const name of students) {
await delay(200);
console.log(`Email sent to ${name}`);
}
console.log("All emails sent");
}
sendEmails(["Rahul", "Priya", "Aman"]);Output:
Email sent to Rahul
Email sent to Priya
Email sent to Aman
All emails sentThe loop processes one item at a time, in order. Use this when order matters or when you must avoid sending too many requests at once.
forEach Does NOT Wait
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function sendEmails(students) {
students.forEach(async (name) => {
await delay(200);
console.log(`Email sent to ${name}`);
});
console.log("All emails sent"); // ❌ runs too early
}
sendEmails(["Rahul", "Priya", "Aman"]);Output:
All emails sent
Email sent to Rahul
Email sent to Priya
Email sent to AmanforEach() calls the async callback for each item but ignores the promises they return, so it doesn't wait for any of them. The same applies to map(), filter(), and other array methods.
Parallel Loop with map() + Promise.all()
To process all items at the same time and wait for all of them:
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function getMarks(name) {
await delay(200);
return { name, marks: name.length * 10 };
}
async function main() {
const names = ["Rahul", "Priya", "Aman"];
const results = await Promise.all(names.map(name => getMarks(name)));
for (const r of results) {
console.log(r.name, r.marks);
}
}
main();Output:
Rahul 50
Priya 50
Aman 40names.map(...) creates an array of promises (all started immediately), and Promise.all() waits for every one of them.
Top-Level await
Normally await is only allowed inside an async function:
function normal() {
await delay(100); // ❌ SyntaxError
}The exception is top-level await (ES2022): inside a JavaScript module, you can use await at the top level of the file, outside any function. This works in browser scripts loaded with <script type="module"> and in Node.js module files (for example, files ending in .mjs). It does not work in regular (non-module) scripts. We'll cover modules in the last chapter of this tutorial.
// inside a module file
const response = await fetch("/api/config");
const config = await response.json();How async/await Fits the Event Loop
Under the hood, the code after an await is resumed as a microtask, just like a .then() callback. Even awaiting a value that isn't a promise pauses the function until the current synchronous code finishes:
async function demo() {
console.log("B");
await null; // await on a non-promise value still pauses
console.log("D");
}
console.log("A");
demo();
setTimeout(() => console.log("E"), 0);
console.log("C");Output:
A
B
C
D
E"D" is a microtask (resumed after await), so it runs before "E", which is a task from setTimeout(). This is the same event loop rule from earlier: synchronous code first, then microtasks, then tasks.
Async Iteration: for await...of
Remember generators? There are also async generators (async function*), which can await inside and yield values over time. You loop over them with for await...of:
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function* fetchPages(totalPages) {
for (let page = 1; page <= totalPages; page++) {
await delay(200); // pretend to download a page
yield `Page ${page} data`;
}
}
async function main() {
for await (const data of fetchPages(3)) {
console.log(data);
}
console.log("Finished");
}
main();Output:
Page 1 data
Page 2 data
Page 3 data
FinishedThis is useful for data that arrives in pieces, such as paginated APIs or streams. for await...of also works on a plain array of promises, awaiting each in order.
Common Mistakes
1. Forgetting await
async function getPrice() {
return 499;
}
async function main() {
const price = getPrice(); // ❌ missing await
console.log(price + 1);
const realPrice = await getPrice(); // ✅
console.log(realPrice + 1);
}
main();Output:
[object Promise]1
500Without await, price is a promise, and adding 1 to it converts the promise to the string "[object Promise]".
2. Using await outside an async function
This is a SyntaxError (except at the top level of a module). Add async to the enclosing function. Note that a callback is its own function: await inside an arrow callback needs that arrow to be async too.
3. Using forEach with async callbacks
As we saw, forEach doesn't wait. Use for...of for one-at-a-time, or Promise.all(array.map(...)) for parallel.
4. Awaiting independent tasks one by one
Unnecessary sequential awaits make your code slower. Use Promise.all() when tasks don't depend on each other.
5. Not handling errors
An async function that throws without a try...catch (and whose caller has no .catch()) causes an unhandled promise rejection. Always handle errors somewhere up the chain.
6. Thinking async makes slow code non-blocking
async doesn't move work to another thread. A heavy synchronous loop inside an async function still blocks the main thread. async/await only helps with waiting (timers, network, files), not with heavy computation.
Promise Chains vs async/await
Promise chain |
|
|---|---|
|
|
|
|
|
|
Values must be passed down the chain | Normal variables stay in scope |
Works anywhere |
|
Both are the same promises underneath, and you can mix them freely. For example, await Promise.all([...]), or calling .catch() on the result of an async function.
Interview Tips
What does an async function return? Always a promise.
Does
awaitblock the main thread? No. It pauses only the current async function; the rest of the program and the event loop keep running.How do you handle errors?
try...catcharoundawait, or.catch()on the returned promise.How do you run async tasks in parallel? Start them all, then
await Promise.all([...]).Why doesn't
forEachwork withawait? It ignores the promises returned by its callback.
Practice ideas:
Rewrite the
Promise.race()timeout example from the previous chapter usingasync/await.Write
async function retry(fn, attempts)that retries a failing async function with atry...catchinside a loop.Process an array of 10 items with at most 2 running at the same time (a "concurrency limit").
Conclusion
async and await let you write promise-based code that reads like synchronous code:
async function main() {
try {
const user = await getUser(); // wait for a promise
const orders = await getOrders(user); // use the result in the next step
console.log(orders);
} catch (error) {
console.log(error.message); // handle any rejection
}
}Remember:
async → the function always returns a promise
await → pause this function until the promise settles, then get its value
errors → use try...catch (or .catch() on the returned promise)
speed → independent tasks: await Promise.all([...])In the next chapters, we'll move to the browser and learn how JavaScript works with web pages through the DOM. Later, in the Fetch API chapter, we'll put async/await to work making real network requests.