Async/Await

Published by Brayan K

How async functions and await let JavaScript wait for promises without blocking: error handling with try/catch, running work in parallel with Promise.all, async loops, and debugging async code.

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

The call gives you a promise; await gives you its result

An async function returns a promise, even when its return statement contains an ordinary value. await waits for that promise’s outcome inside the current async flow. These examples use local fixtures and resolved promises, so their results do not depend on a network, a timer duration or the clock.

async function readTitle(id) {
  const records = { a: { title: "Loops" }, b: { title: "Functions" } };
  const record = await Promise.resolve(records[id]); // Suspend this invocation until its local result is available.
  if (record === undefined) throw new Error("Unknown item: " + id);
  return record.title.toUpperCase();
}
console.log("before call");
const pending = readTitle("a"); // The call returns a promise, not the title.
console.log(pending instanceof Promise);
console.log("after call");
const title = await pending; // Read the fulfilled value at the caller boundary.
console.log(title);

// ✅ Expected output:
// before call
// true
// after call
// LOOPS

The returned promise represents an eventual result; it is not the record itself. The top-level await in these complete examples runs in this editor and in a JavaScript module. In an ordinary script, put awaited code inside an async function. JavaScript Modules: ES6 Imports, Exports, Bundling owns module setup.

async function readUser() {
  return { name: "Ada" };
}
const pending = readUser();
console.log(pending.name);
const user = await pending;
console.log(user.name);

// ✅ Expected output:
// undefined
// Ada
async function missingReturn() {
  await Promise.resolve("ready");
}
async function withReturn() {
  return await Promise.resolve("ready");
}
console.log(await missingReturn());
console.log(await withReturn());

// ✅ Expected output:
// undefined
// ready

Suspension happens at await, not at the function’s first line

Calling an async function starts executing its body. Its synchronous work before the first await runs immediately. At await, even an already-fulfilled promise allows the continuation to run later. This trace observes ordering without claiming a duration.

async function work() {
  console.log("inside before await");
  await Promise.resolve();
  console.log("inside after await");
}
console.log("caller before");
const pending = work();
console.log("caller after");
await pending;
console.log("joined");

// ✅ Expected output:
// caller before
// inside before await
// caller after
// inside after await
// joined

async does not move a calculation onto another thread. A long synchronous loop inside an async function still occupies the thread running that function. Web Workers (Background Threads) owns background execution; Event Loop, Microtasks & Async Internals owns detailed scheduling.

async function addSmallRange() {
  let total = 0;
  for (let value = 1; value <= 4; value++) total += value;
  console.log("calculated", total);
  return total;
}
const pending = addSmallRange();
console.log("call returned");
console.log(await pending);

// ✅ Expected output:
// calculated 10
// call returned
// 10

await is not permitted inside an ordinary nested function just because an outer function is async. Each function has its own syntax context. Mark the function that contains await as async, then handle the promise it returns. This diagnostic compiles a fixed ordinary-function body so the error comes from the same syntax context in both the editor and Node.

new Function("return await Promise.resolve(3);")();

// ✅ Expected error:
// SyntaxError: await is only valid in async functions and the top level bodies of modules

Catch the awaited rejection at the boundary that owns it

A throw inside an async function rejects its returned promise. An ordinary try/catch around only the call does not catch that later rejection. Await the promise inside the try, or attach a rejection handler. Error Handling owns choosing error types, preserving context and deciding what can recover.

async function fail() {
  throw new Error("Item unavailable");
}
console.log("before");
await fail();
console.log("unreachable");

// ✅ Expected output:
// before

// ✅ Expected error:
// Error: Item unavailable
async function fail() {
  throw new Error("Item unavailable");
}
let pending;
try {
  pending = fail();
  console.log("call returned");
} catch (error) {
  console.log("call caught", error.message);
}
try {
  await pending;
} catch (error) {
  console.log("await caught", error.message);
}

// ✅ Expected output:
// call returned
// await caught Item unavailable

Returning a promise from inside try passes its outcome to the caller, but the surrounding catch does not await it. return await makes a local catch or finally wait for the operation at that boundary. It is not a rule to add or remove await from every return.

async function fail() { throw new Error("missing"); }
async function passThrough() {
  try { return fail(); }
  catch { return "handled locally"; }
}
async function handleHere() {
  try { return await fail(); }
  catch { return "handled locally"; }
}
console.log(await passThrough().catch(error => "caller saw " + error.message));
console.log(await handleHere());

// ✅ Expected output:
// caller saw missing
// handled locally

Choose dependencies before choosing sequential or concurrent work

Await each step when the next step depends on its result. If operations are independent, start them before awaiting their combined result. Promise.all joins the promises you provide; it does not call function values or move CPU work into parallel threads. Mastering Promises: Chaining, Error Flow & Patterns owns promise chaining and settlement.

async function work(label) {
  console.log("start", label);
  await Promise.resolve();
  console.log("finish", label);
  return label;
}
const first = await work("A");
const second = await work(first + "B");
console.log(first, second);

// ✅ Expected output:
// start A
// finish A
// start AB
// finish AB
// A AB
async function work(label) {
  console.log("start", label);
  await Promise.resolve();
  console.log("finish", label);
  return label;
}
const first = work("A");
const second = work("B");
console.log("both started");
console.log(JSON.stringify(await Promise.all([first, second])));

// ✅ Expected output:
// start A
// start B
// both started
// finish A
// finish B
// ["A","B"]

The result array follows input order, not completion order. A rejection rejects the combined promise, but does not automatically cancel other work. Do not claim a fixed speedup: actual completion depends on the operations and environment. Cancellation belongs to AbortController & Cancelling Async Work.

let releaseA, releaseB;
const a = new Promise(resolve => { releaseA = resolve; });
const b = new Promise(resolve => { releaseB = resolve; });
const combined = Promise.all([a, b]);
releaseB("B");
releaseA("A");
console.log(JSON.stringify(await combined));

// ✅ Expected output:
// ["A","B"]
let finishOther;
let finished = false;
const other = new Promise(resolve => { finishOther = resolve; })
  .then(() => { finished = true; return "other completed"; });
try {
  await Promise.all([Promise.reject(new Error("first failed")), other]);
} catch (error) {
  console.log(error.message, finished);
}
finishOther();
console.log(await other, finished);

// ✅ Expected output:
// first failed false
// other completed true

A loop must actually join the promises it starts

forEach calls its callback but ignores the callback’s return value. Making that callback async does not make forEach wait. This broken total returns its current number before either callback resumes.

async function brokenTotal(values) {
  let total = 0;
  values.forEach(async value => {
    await Promise.resolve();
    total += value;
  });
  return total;
}
console.log(await brokenTotal([2, 3]));

// ✅ Expected output:
// 0

Use for...of with await for deliberate sequential work. Use map to collect promises, then await Promise.all when all operations may start independently. A map result is initially an array of promises, not the final transformed values.

async function totalInOrder(values) {
  let total = 0;
  for (const value of values) {
    total += await Promise.resolve(value);
  }
  return total;
}
console.log(await totalInOrder([2, 3]));
console.log(await totalInOrder([]));

// ✅ Expected output:
// 5
// 0
async function double(value) { return value * 2; }
const pending = [2, 3].map(double);
console.log(pending[0] instanceof Promise);
const values = await Promise.all(pending);
console.log(JSON.stringify(values));
console.log(JSON.stringify(await Promise.all([])));

// ✅ Expected output:
// true
// [4,6]
// []

Starting an unbounded number of requests can overload a service even when Promise.all waits correctly. Async/Await Architecture & Best Practices owns concurrency limits and broader coordination patterns. HTTP status and response-body checks belong to Fetch API.

Guided exercise: return the joined values

Fill the async modifier, the join operation and the returned value. Keep the array of promises separate from the final array, and check the empty-input behaviour too.

___ function doubled(values) { // 👉 replace ___ with async
  const pending = values.map(async value => value * 2);
  const result = await ___.all(pending); // 👉 replace ___ with Promise
  return ___; // 👉 replace ___ with result
}
console.log(JSON.stringify(await doubled([2, 4])));
console.log(JSON.stringify(await doubled([])));

// ✅ Expected output:
// [4,8]
// []

Independent brief: stop a sequence when a lookup fails

Write loadNames(ids, readName). Await each readName(id) in input order and return the collected names. If a lookup rejects, let that rejection reach the caller and do not start later lookups. An empty input should return an empty array without calling readName. The supplied reader returns a promise for a name string or rejects; there is no network in this exercise.

Check the successful order, the empty case and a failure in the middle. Keep the input ID array unchanged. A failed run should not return a plausible partial list as if it were complete.

async function loadNames(ids, readName) {
  const names = [];
  for (const id of ids) {
    names.push(await readName(id));
  }
  return names;
}
const namesById = { a: "Ada", b: "Bo", c: "Chen" };
const calls = [];
async function readName(id) {
  calls.push(id);
  if (!Object.hasOwn(namesById, id)) throw new Error("Unknown ID: " + id);
  return namesById[id];
}
const ids = ["b", "a"];
const before = JSON.stringify(ids);
console.log(JSON.stringify(await loadNames(ids, readName)));
console.log(calls.join(","), JSON.stringify(ids) === before);
calls.length = 0;
console.log(JSON.stringify(await loadNames([], readName)), calls.length);
try {
  await loadNames(["a", "missing", "c"], readName);
} catch (error) {
  console.log(error.name + ": " + error.message);
}
console.log(calls.join(","));

// ✅ Expected output:
// ["Bo","Ada"]
// b,a true
// [] 0
// Error: Unknown ID: missing
// a,missing

Practice quiz

What does this complete program print? async function value() { return 7; } const pending = value(); console.log(pending instanceof Promise); console.log(await pending);

  • true 7
  • false 7
  • true undefined
  • false undefined

Answer: true 7. An async call returns a promise; awaiting it gives the returned value.

What does this complete program print? async function work() { console.log("A"); await 1; console.log("C"); } const pending = work(); console.log("B"); await pending;

  • A C B
  • A B C
  • B A C
  • C A B

Answer: A B C. The initial body runs synchronously, then await yields before the continuation.

What does this complete program print? async function value() { await Promise.resolve(9); } console.log(await value());

  • 9
  • null
  • undefined
  • Promise

Answer: undefined. Waiting does not return the awaited value. Reaching the end returns undefined through the promise.

What does this complete program print? async function fail() { throw new Error("missing"); } let pending; try { pending = fail(); console.log("returned"); } catch { console.log("call caught"); } try { await pending; } catch { console.log("await caught"); }

  • call caught
  • returned
  • call caught await caught
  • returned await caught

Answer: returned await caught. The async call returns a rejected promise; the await observes its rejection inside the second try.

What does this complete program print? let resolveA, resolveB; const a = new Promise(resolve => { resolveA = resolve; }); const b = new Promise(resolve => { resolveB = resolve; }); const result = Promise.all([a, b]); resolveB("second"); resolveA("first"); console.log(JSON.stringify(await result));

  • ["first","second"]
  • ["second","first"]
  • ["first"]
  • ["second"]

Answer: ["first","second"]. Promise.all returns values in the order of its input promises, regardless of which settles first.

What does this complete program print? async function total() { let result = 0; [1, 4].forEach(async value => { await Promise.resolve(); result += value; }); return result; } console.log(await total());

  • 5
  • 0
  • 4
  • undefined

Answer: 0. forEach does not join its callback promises. The current number is returned before the callbacks resume.

What does this complete program print? async function label(value) { return "item-" + value; } const pending = [1, 2].map(label); console.log(pending[0] instanceof Promise); console.log(JSON.stringify(await Promise.all(pending)));

  • false ["item-1","item-2"]
  • true [1,2]
  • true ["item-1","item-2"]
  • false [1,2]

Answer: true ["item-1","item-2"]. map collects the returned promises; Promise.all joins them into the ordered values.

What does this complete program print? async function fail() { throw new Error("missing"); } async function outer() { try { return await fail(); } catch { return "fallback"; } } console.log(await outer());

  • undefined
  • missing
  • Promise
  • fallback

Answer: fallback. The awaited rejection occurs within the try, so this catch returns the explicit fallback.

Continue this course

Related lessons