P

Promises

Promises represent eventual completion or failure of async operations, with full type support.

Code

typescript
1// Creating a typed Promise
2function fetchUser(id: number): Promise<{ id: number; name: string }> {
3 return new Promise((resolve, reject) => {
4 setTimeout(() => {
5 if (id > 0) {
6 resolve({ id, name: `User ${id}` });
7 } else {
8 reject(new Error("Invalid user ID"));
9 }
10 }, 100);
11 });
12}
13
14// Promise chaining
15fetchUser(1)
16 .then((user) => {
17 console.log(`Found: ${user.name}`);
18 return user.id;
19 })
20 .then((id) => {
21 console.log(`User ID: ${id}`);
22 })
23 .catch((error: Error) => {
24 console.error(`Error: ${error.message}`);
25 });
26
27// Promise.all - run promises in parallel
28async function fetchAllUsers(ids: number[]): Promise<{ id: number; name: string }[]> {
29 const promises = ids.map((id) => fetchUser(id));
30 return Promise.all(promises);
31}
32
33// Promise.race - first to complete wins
34function timeout<T>(promise: Promise<T>, ms: number): Promise<T> {
35 const timeoutPromise = new Promise<never>((_, reject) => {
36 setTimeout(() => reject(new Error("Timeout")), ms);
37 });
38 return Promise.race([promise, timeoutPromise]);
39}
40
41// Promise.allSettled - wait for all, regardless of success/failure
42async function fetchWithStatus(ids: number[]) {
43 const results = await Promise.allSettled(ids.map((id) => fetchUser(id)));
44
45 results.forEach((result, index) => {
46 if (result.status === "fulfilled") {
47 console.log(`User ${ids[index]}: ${result.value.name}`);
48 } else {
49 console.log(`User ${ids[index]} failed: ${result.reason}`);
50 }
51 });
52}
53
54fetchWithStatus([1, 2, -1, 3]);

Run this example locally

$ npx ts-node async/promises.ts