×

typescript · level 2 · unit 6 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.