AI Hints
Home›TypeScript Tutorial›Async and Outside Data
TypeScript · Lesson 79 of 120

Promises and async

Typed waiting.

⏱ 2 min read▶ Video at 1:01:40🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

Slow work, like network calls, returns a promise. A promise of T is a value of type T that arrives later. Await waits for it, and gives you the T.

Promises and async
From the video: Promises and async
  • Slow work
  • Promise<T>
  • await gives T

A typed async function

Check stock returns a promise of a number. Await gives us a plain number. Promise dot all waits for several at once. Run it.

app.tstypescript
async function checkStock(store: string): Promise<number> {
  await new Promise(resolve => setTimeout(resolve, 100));
  return store === "Leeds" ? 12 : 5;
}

const leeds: number = await checkStock("Leeds");
const all = await Promise.all(["York", "Hull"].map(checkStock));

console.log("Leeds:", leeds, "| others:", all);
Output
Leeds: 12 | others: [ 5, 5 ]

Summary

Async functions return Promise of T, and await unwraps it. Next, typing JSON from outside.

Key takeaways
  • Promise<number>
  • await
  • Promise.all
Next up: Typing JSON — data from outside