typescript · level 2 · unit 6 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A is a value that arrives later, and waits for it.
Callbacks get messy when one wait follows another. A promise is a stand-in for a value that is not ready yet, like a ticket at a takeaway. Its type says what will arrive: Promise<string>, or Promise<void> for nothing.
Inside a function marked , write await before a promise and the function pauses until the value arrives. The rest of the program keeps running meanwhile. An async function always hands back a promise.
Scripts cannot await outside a function, so put your steps in async function main() and call main(); at the bottom. new Promise builds one by hand: call resolve when it is ready.
function wait(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(() => resolve(), ms));
}
async function main(): Promise<void> {
console.log("Order placed");
await wait(200);
console.log("Pizza ready!");
}
main();
console.log("Waiting..."); Gwecode waits for unfinished promises too, for up to five seconds.
guess first
A promise that is ready at once. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
async function cook(): Promise<string> {
return "pancakes";
}
async function main(): Promise<void> {
console.log("Start");
const food = await cook();
console.log(`Breakfast: ${food}`);
}
main();
console.log("Laying the table");
your turn
Your turn. Wait for the bus.
Fill in the type the promise will hand over, then the word that makes main wait for the bus to arrive.
fix it
await only works in one place. Fix it!
- Read the error:
TS1308: 'await' expressions are only allowed within async functions. mainis a plain function. Mark itasync, and remember that anasyncfunction hands back a promise.- Change line 4 to
async function main(): Promise<void> {then press run.
nailed it
your code can wait without getting stuck. :D
- A promise stands in for a value that arrives later.
awaitpauses anasyncfunction until the value is ready.- Put your steps in
async function main()and callmain();.
new words in your collection
- promise
- async
- await
This lesson isn’t saved. A free account remembers every lesson you finish.