An async function always returns a promise
Put async before a function definition when it needs await. Returning a value fulfills its returned promise; throwing rejects it. Even async function count() { return 2; } returns a promise, not a plain 2. Await extracts the fulfillment value or throws the rejection reason inside the awaiting function.
Await pauses that function's continuation. It does not block the browser's event loop, freeze other event handlers, or make unrelated work wait. Values that are not promises can also be awaited, but that rarely needs to be a design choice.
Use try/catch around an awaited operation when you can choose a useful response. A catch that logs and returns nothing turns failure into a fulfilled undefined result; that can hide the problem from its caller. Decide whether to recover with a documented value or rethrow. A finally block runs after success or failure and is useful for releasing resources, not for silently replacing the result.
Each example supplies its own local asynchronous function. No network request is involved yet. This lets you learn control flow before adding response status codes and remote data.
A consistent entry point for the examples
From here onward, async examples use async function main() { ... } followed by main();. The first line defines the program's async entry; the final call starts it and returns its promise. The editor waits for that promise, so it can capture the complete result. Keep main() as the last statement when editing; put extra program steps inside main.
Inside main, await can extract each result and try/catch can handle rejection. An inner function such as loadTitle is an ordinary helper; putting it inside main keeps the example self-contained. You can later move helpers into modules without changing what they return. This explicit entry point also works in a classic webpage script; you do not need top-level await for these exercises.
Predict and trace
Write the output before running. Follow the values through each call; if your prediction differs, identify the first step that surprised you.
async function main() {
async function loadTitle() {
return "Notes";
}
async function fail() {
throw new Error("Unavailable");
}
console.log(await loadTitle());
try {
await fail();
} catch (error) {
console.log(error.message);
} finally {
console.log("Attempt finished");
}
}
main();Check your prediction
Notes
Unavailable
Attempt finishedWithout await inside try, the rejection would occur after the try block had already moved on.
Returning an object from an arrow function
Tests in this course replace real loaders with small stand-ins such as async () => ({ name: "Ada" }). The parentheses around the braces matter. After =>, a { starts a function body, not an object. So () => { ok: true } is a body containing a statement labelled ok, and it returns undefined. Wrapping the object in parentheses makes it an expression to return.
const withParens = () => ({ ok: true });
const withoutParens = () => { ok: true };
console.log(withParens().ok);
console.log(withoutParens());Check your prediction
true
undefinedWith two properties the mistake is louder: () => { ok: true, status: 200 } is not valid as a body, and the program stops with SyntaxError: Unexpected token ':' before anything runs. Either way the fix is the same: () => ({ ok: true, status: 200 }), or a block body with an explicit return { … };.
Debug a plausible mistake
Repair the missing promise return
Await addOne and print 3. Keep load asynchronous and let rejection propagate to main. Explain why awaiting a helper that returns undefined cannot wait for the promise it discarded.
Predict the supplied program's actual behavior first. It runs without an error, but breaks the requirement. Make a small repair, then try a case that would distinguish the repaired version from the original.
async function load() {
return 2;
}
function addOne() {
load().then(value => value + 1);
}
async function main() {
console.log(await addOne());
}
main();Hint 1: the idea
An ordinary helper must return the promise it wants its caller to observe.
Hint 2: a first step
Return the then chain, or make the helper async and return its awaited calculation.
Show one solution
async function load() {
return 2;
}
function addOne() {
return load().then(value => value + 1);
}
async function main() {
console.log(await addOne());
}
main();3The original printed undefined. addOne started the chain but returned nothing, so await addOne() awaited undefined and finished immediately, while the + 1 result was computed later and thrown away. Returning the chain hands the caller the promise to wait on, and a rejection from load now reaches main's await instead of becoming an unhandled rejection.
Trace the contract before building
An async call returns a promise even when its body returns an ordinary number. Await pauses that function's continuation until fulfillment or rejection; it does not pause all JavaScript execution. Other already-scheduled work can progress during the wait.
Trace which statements run before the first await and which run afterward. Keep independent operations separate from ones that genuinely depend on earlier values. Add rejection to the trace too: it follows the enclosing try/catch policy, not the next successful calculation. The console entry must retain the promise representing the work it expects to finish.
Build it yourself
async / await: practice
Write async label(load), which awaits a loader function and returns "Book: " followed by its title. Let failures reach the caller. Print a success and a caught rejection.
async function main() {
// Call load(), await it, and return a string.
}
main();Hint 1: the idea
The function receives an operation, not a promise created elsewhere.
Hint 2: a first step
An uncaught throw in async label rejects label’s returned promise.
Show one solution
async function main() {
async function label(load) {
const title = await load();
return `Book: ${title}`;
}
console.log(await label(async () => "The Web"));
try {
await label(async () => {
throw new Error("Offline");
});
} catch (error) {
console.log(error.message);
}
}
main();Book: The Web
OfflineReplace the loader with one returning an empty title. An async success is not automatically a valid domain value; decide which layer should reject it.
Test a changed requirement
Replace the loader with one returning an empty title. An async success is not automatically a valid domain value; decide which layer should reject it.
Explain before moving on
Why must the caller await label? What changes if you catch and return undefined instead of propagating failure?
Completion is saved in this browser only. It does not measure mastery.