Async & Await
async and await let you write promise-based code that reads from top to bottom, like ordinary step-by-step code. Under the hood they still use promises, but you lose the long .then chains and can handle errors with familiar try/catch.
async functions
Putting async before a function changes two things: the function always returns a promise, and you may use await inside it. A normal return value is wrapped in a fulfilled promise; a thrown error becomes a rejected one.
async function getNumber() {
return 7;
}
console.log(getNumber());
getNumber().then((n) => console.log(n));
The arrow-function form is const getNumber = async () => 7;, and methods can be async too.
await
await promise pauses the async function until the promise settles, then gives you its value. Only that function pauses: the rest of the page, and code outside the function, keeps running.
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function makeChai() {
console.log("Boiling water...");
await wait(1000);
console.log("Adding tea leaves...");
await wait(500);
return "Chai is ready";
}
makeChai().then((message) => console.log(message));
console.log("Meanwhile, setting the table");
The function runs normally until its first await. There it pauses and hands control back, so "Meanwhile, setting the table" logs second. When the promise fulfils, the rest of the function continues as a microtask (see the event loop).
await simply lets you read them top to bottom, and catch handles a failure at any step.Handling errors with try/catch
If an awaited promise rejects, await throws the rejection reason as an error at that line. Catch it with try/catch, exactly like a synchronous error, and use finally for clean-up.
function payFees(amount) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (amount > 0) resolve(`Paid KES ${amount}`);
else reject(new Error("Amount must be positive"));
}, 300);
});
}
async function run() {
try {
console.log(await payFees(2500));
console.log(await payFees(0));
console.log("not reached");
} catch (error) {
console.log("Error:", error.message);
} finally {
console.log("Receipt printed");
}
}
run();
You can also handle the error where you call the function: run().catch(...). Remember that an async function's errors become a rejected promise, so somebody must catch them. More on this in Error Handling.
Sequential or parallel?
Each await waits for the previous one. That is right when a step needs the result of the one before it, but wasteful when the jobs are independent.
const after = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
async function sequential() {
const start = Date.now();
const a = await after(1000, "maize");
const b = await after(1000, "beans");
console.log(a, b, Date.now() - start);
}
async function parallel() {
const start = Date.now();
const [a, b] = await Promise.all([after(1000, "maize"), after(1000, "beans")]);
console.log(a, b, Date.now() - start);
}
Calling sequential() takes about two seconds; calling parallel() takes about one, because both timers run at the same time (the exact milliseconds will be slightly higher on your machine):
await in loops
To process items one after another, use for...of with await inside an async function. Don't use forEach: it ignores the promises your callback returns and doesn't wait.
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function remindAll(names) {
for (const person of names) {
await wait(200);
console.log("SMS sent to", person);
}
console.log("All reminders sent");
}
remindAll(["Amina", "Baraka"]);
With names.forEach(async (person) => {...}) instead, "All reminders sent" would log first, before any SMS.
Forgetting await. const data = getData(); gives you a pending promise, not the data, so data.name is undefined. The opposite mistake, using await inside a function that isn't async, is a SyntaxError. (In ES modules you may also use await at the top level of the file.)
Key points
- An
asyncfunction always returns a promise;awaitpauses it until a promise settles. - Only the async function pauses; other code and the page keep running.
- A rejected promise makes
awaitthrow, so wrap awaits intry/catch/finally. - Use
Promise.allfor independent jobs andfor...of(notforEach) for one-at-a-time loops.
Tip: use the ← and → keys to move between pages.
