Promises and await
Some things take a while before they give you a result: a server sends data, a pizzeria bakes a pizza. JavaScript doesn't stop and wait for them: the page would freeze, and no button would work in the meantime. Instead, such a function returns a Promise straight away: an object that promises to give you a value later. It's like the buzzer you get when you order at a food stand: you get it at once, and the food comes later.
At the top of script.js, there's a ready-made function orderPizza(). It pretends to be a pizzeria: it returns a Promise, and a second later, the Promise gets its value, a text such as "Your Margherita is ready!". Inside the function, new Promise(...) creates the Promise, and resolve(...) gives it its value. You won't need to write such functions yourself: in the next lesson, Promises will come from the browser's function fetch().
If you use the result as it is, you get the Promise, not the pizza:
const pizza = orderPizza("Margherita");
console.log(pizza); // Prints: Promise {}To get the value, wait for it with await:
orderButton.addEventListener("click", async function () {
const pizza = await orderPizza("Margherita");
message.textContent = pizza;
});await waits until the Promise has its value and then gives it to you. You may use it only in a function marked async, which you write before the word function. Without async, the script doesn't run at all, and the console shows SyntaxError: await is only valid in async functions and the top level bodies of modules.
While the function waits, the rest of the page doesn't: buttons work, and timers keep running. Only this one function pauses at await and goes on once the value arrives.
In other people's code, you'll also see .then(): orderPizza("Margherita").then(function (pizza) { ... }). It does the same as await, written another way. In this course, we use await, which reads from top to bottom.
Instructions
When orderButton is clicked, order a Margherita: in a handler marked async, wait for orderPizza("Margherita") with await, and show the text you get in message.
For a whole second, the page shows nothing, and the user doesn't know whether the click worked. Before the await, show Baking your pizza… in message. That's how pages tell you that they're loading something.