When Something Fails
Waiting doesn't always end well: the server doesn't answer, the pizzeria is closed, the coupon has expired. Then the Promise doesn't get a value; instead, it's rejected with an error. await then throws the error, just like a mistake in your code: the rest of the function doesn't run, and the console shows the error.
In this exercise, the ready-made function checkCoupon() asks the pizzeria about a coupon. A second later, it gives the discount in percent, or, for a code the pizzeria doesn't know, it fails with an error such as The coupon ABC doesn't exist. Inside the function, reject(...) is what rejects the Promise.
To deal with the error yourself, put the code that can fail into try, and what should happen if it fails into catch:
try {
const discount = await checkCoupon(code);
message.textContent = `You get ${discount}% off!`;
} catch (error) {
message.textContent = error.message;
}JavaScript runs the code in try. If everything works, it skips catch. If a line throws an error, it jumps straight to catch, and the lines left in try don't run. In the parentheses after catch, you get the error: an object whose property message is its text. The console then shows nothing, because you've handled the error.
After catch, you can add finally. Its code runs at the end in both cases, whether the code in try worked or failed. That's the right place for tidying up, such as enabling a button again:
try {
// What can fail
} catch (error) {
// What to do if it fails
} finally {
checkButton.disabled = false;
}Typical mistakes:
message.textContent = error;shows the error with its type in front:Error: The coupon ABC doesn't exist.The text alone is inerror.message.trycatches the error of a Promise only when you wait for the Promise withawaitinsidetry.
Instructions
When checkButton is clicked, check the code typed into couponInput: wait for checkCoupon() with await, and show the discount in message, for example You get 10% off! for the code PIZZA10.
Type a coupon that doesn't exist, such as ABC, and click: the page doesn't change, and the console shows the error. Put the lines of the handler that wait for checkCoupon() and show the discount into try, and in catch, show the error's message in message.
While the pizzeria checks the code, show Checking… and disable checkButton. Enable it again in finally, so that it works again whether the coupon was valid or not.