A failed lookup is not free delivery
If the delivery service cannot supply a charge, showing a total with charge zero is misleading. For this exercise, the quote should become unavailable with an explanation.
async function lookupDeliveryCharge(available) {
if (!available) throw new Error("Delivery charge unavailable");
return 5;
}
async function prepareQuote(subtotal, available) {
try {
const charge = await lookupDeliveryCharge(available);
return { ok: true, total: subtotal + charge };
} catch (error) {
return { ok: false, message: error.message };
}
}
async function runChecks() {
const success = await prepareQuote(40, true);
const failure = await prepareQuote(40, false);
console.assert(success.ok && success.total === 45);
console.assert(!failure.ok && failure.total === undefined);
}
runChecks().catch((error) => console.error(error));
Throwing inside an async function rejects its returned promise. Await converts that rejection into a throw at the await point, allowing the surrounding catch to handle it. This example controls the thrown Error; adapt error formatting defensively at an external boundary.
Guided trap
Calling an asynchronous function inside try without awaiting or returning its promise does not make later rejection part of that synchronous try path. The failure needs an awaited path or a promise catch.
Do not add automatic retries without a policy. Repeating a read may be acceptable; repeating a state-changing operation can duplicate work. This course uses simulations and does not contact a real service.
Independent exercise
Add a pending message before awaiting the quote, then display either the total or the failure explanation based on ok. Run both scenarios. What would change if the lookup fulfilled with a negative charge?
Correction
The fulfilled negative amount would need validation; catch does not run merely because a value violates a rule. Validate the received number before using it. A clear outcome distinguishes pending, available and unavailable rather than representing all three with zero.
Review
Success in transport or scheduling is not success in the domain. Preserve that distinction when the future web course introduces real requests.