Lesson 24 of 56
TypescriptAsync/Await with Types
20 minutes
Course progress43%
Async Functions
async function delay(ms: number): Promise<void> {
return new Promise( (resolve, ms));
}
(): <> {
();
;
}
Lesson 24 of 56
Typescript20 minutes
async function delay(ms: number): Promise<void> {
return new Promise( (resolve, ms));
}
(): <> {
();
;
}
function getNumber(): Promise<number> { /* … */ }
If you forget to await, the function returns a Promise<...> which may cause type mismatches.
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;
}
}
Promise.allasync function loadAll(urls: string[]): Promise<string[]> {
const promises = urls.map(u => fetch(u).then(r => r.text());
return Promise.all(promises);
}