Promises and async / await
Type asynchronous functions as Promise<T> and wait for them with await.
Runs in Zerethon IDE · TypeScript 7
Official TypeScript documentation ↗
main.ts
const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
async function job(name: string, ms: number): Promise<string> {
await sleep(ms);
return `${name} done`;
}
async function main(): Promise<void> {
const results = await Promise.all([job('a', 30), job('b', 10)]);
console.log(results);
try {
throw new Error('boom');
} catch (err) {
console.log('caught:', err instanceof Error ? err.message : err);
}
}
main();
Output
[ 'a done', 'b done' ] caught: boom
In strict mode a caught error has type unknown: check err instanceof Error before reading err.message.