Lesson 24 of 56 · Typescript
Async/Await with Types
Duration: 20 minutes
Async Functions
async function delay(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function fetchData(): Promise<string> {
await delay(500);
return "done";
}
Return Types
function getNumber(): Promise<number> { /* … */ }
If you forget to await, the function returns a Promise<...> which may cause type mismatches.
Error Handling
async function safeFetch(url: string): Promise<string | null> {
try {
const r = await fetch(url);
if (!r.ok) throw new Error(r.statusText);
return await r.text();
} catch (e) {
console.error(e);
return null;
}
}
Parallel Await with Promise.all
async function loadAll(urls: string[]): Promise<string[]> {
const promises = urls.map(u => fetch(u).then(r => r.text());
return Promise.all(promises);
}