Keep dependent steps together
The total needs a delivery charge. Async/await expresses this dependency in a familiar sequence without pretending the charge is available immediately.
function lookupDeliveryCharge() {
return Promise.resolve(5);
}
async function calculateDeliveredTotal(subtotal) {
const charge = await lookupDeliveryCharge();
return subtotal + charge;
}
async function runExample() {
const total = await calculateDeliveredTotal(40);
console.assert(total === 45);
console.log(total);
}
runExample().catch((error) => console.error(error));
An async function always returns a promise. Await pauses that function's continuation until the awaited value is resolved; it does not block the whole JavaScript environment. The caller of calculateDeliveredTotal must also handle its promise rather than adding it to a number.
We wrap examples in async functions so they work in the practice environment without depending on top-level await support. The final catch handles a failed run. In these controlled examples we expect no failure; the next lesson exercises it intentionally.
Guided review
Writing const charge = lookupDeliveryCharge() without await stores a promise, not the numeric charge. A debugger can reveal this, but the function contract should make it predictable before execution.
Await does not validate the result. A fulfilled promise containing invalid data is still a successful asynchronous operation with invalid business input.
Independent exercise
Create a simulated discount lookup returning a fulfilled promise with 10. Await it, subtract it from subtotal 100 and verify 90. Explain whether delivery and discount must be fetched sequentially if neither depends on the other.
Correction
Use an async function, await the discount, then calculate 100 minus 10. Independent requests can be started together; Promise.all can await both, but sequential code is easier to introduce first. Do not parallelize operations that depend on each other's results or ordering.
Review
Read an async function in two layers: business dependencies and possible suspension points. The syntax is convenient, but its returned promise remains part of the contract.