Async and await in TypeScript
Wait for promises with typed results. Press Run to try it, then change the code and run it again.
const wait = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
async function fetchScore(player: string): Promise<number> {
await wait(300);
return player.length * 10;
}
const scores = await Promise.all(['Asha', 'Rohan', 'Mei'].map(fetchScore));
console.log('Scores:', scores);
Output
Press Run to see the output.
More TypeScript examples
- Hello, World · Print a line of text with a typed variable.
- Interfaces and objects · Describe the shape of an object and use it in a function.
- Generics · Write one function that works with any type, safely.
- Union types and narrowing · Handle values that can be one of several types.
- Catch a type error · See how TypeScript stops a bug before the code runs.