-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathasync_promises.ts
More file actions
144 lines (128 loc) · 3.49 KB
/
async_promises.ts
File metadata and controls
144 lines (128 loc) · 3.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
/**
* Async/Await and Promises
*
* Asynchronous programming is crucial for handling I/O operations,
* API calls, and non-blocking code execution.
*
* Key Concepts:
* - Promises (resolve, reject, then, catch)
* - Async/await syntax
* - Promise chaining
* - Error handling
* - Promise.all, Promise.race, Promise.allSettled
*/
// Basic Promise
function fetchUser(id: number): Promise<{ id: number; name: string }> {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (id > 0) {
resolve({ id, name: `User ${id}` });
} else {
reject(new Error("Invalid user ID"));
}
}, 1000);
});
}
// Promise Chaining
fetchUser(1)
.then(user => {
console.log("User:", user);
return fetchUser(user.id + 1);
})
.then(nextUser => {
console.log("Next user:", nextUser);
})
.catch(error => {
console.error("Error:", error.message);
});
// Async/Await
async function getUserData(id: number) {
try {
const user = await fetchUser(id);
console.log("User data:", user);
return user;
} catch (error) {
console.error("Failed to fetch user:", error);
throw error;
}
}
// Multiple Async Operations
async function fetchMultipleUsers(ids: number[]) {
// Sequential (one after another)
const users1: any[] = [];
for (const id of ids) {
const user = await fetchUser(id);
users1.push(user);
}
// Parallel (all at once)
const users2 = await Promise.all(
ids.map(id => fetchUser(id))
);
return users2;
}
// Promise.all - Wait for all, fail if any fails
async function fetchAllData() {
const [users, posts, comments] = await Promise.all([
fetchUser(1),
fetchUser(2),
fetchUser(3)
]);
return { users, posts, comments };
}
// Promise.allSettled - Wait for all, get results even if some fail
async function fetchAllSettled() {
const results = await Promise.allSettled([
fetchUser(1),
fetchUser(-1), // This will fail
fetchUser(3)
]);
results.forEach((result, index) => {
if (result.status === "fulfilled") {
console.log(`Promise ${index} succeeded:`, result.value);
} else {
console.log(`Promise ${index} failed:`, result.reason);
}
});
}
// Promise.race - Return first resolved/rejected
async function fetchWithTimeout(url: string, timeout: number) {
const fetchPromise = fetch(url);
const timeoutPromise = new Promise((_, reject) =>
setTimeout(() => reject(new Error("Timeout")), timeout)
);
return Promise.race([fetchPromise, timeoutPromise]);
}
// Error Handling Patterns
async function robustFetch(id: number) {
try {
return await fetchUser(id);
} catch (error) {
// Log error
console.error("Fetch error:", error);
// Return default or rethrow
return { id: 0, name: "Unknown" };
}
}
// Async Generator
async function* asyncGenerator() {
for (let i = 1; i <= 3; i++) {
await new Promise(resolve => setTimeout(resolve, 1000));
yield await fetchUser(i);
}
}
// Using async generator
async function processAsyncGenerator() {
for await (const user of asyncGenerator()) {
console.log("Generated user:", user);
}
}
export {
fetchUser,
getUserData,
fetchMultipleUsers,
fetchAllData,
fetchAllSettled,
fetchWithTimeout,
robustFetch,
asyncGenerator
};