-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPromises.js
More file actions
219 lines (189 loc) · 4.73 KB
/
Promises.js
File metadata and controls
219 lines (189 loc) · 4.73 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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("start");
}, 2000);
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("step 1");
}, 4000);
});
const promise3 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("step 2");
}, 6000);
});
const promise4 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("step 3");
}, 1000);
});
const collect = [promise1, promise2, promise3, promise4];
collect
.reduce((prevPromise, currPromise) => {
return prevPromise.then((value) => {
return currPromise.then((res) => {
return value + res;
});
});
}, Promise.resolve(""))
.then((finalres) => {
console.log(finalres);
});
const tasks = [
() => Promise.resolve(10),
() => Promise.resolve(20),
() => Promise.resolve("STOP"),
() => Promise.resolve(40),
() => Promise.resolve(50),
];
let shouldStop = false;
const final = tasks.reduce((prevPromise, currPromise) => {
return prevPromise.then((res) => {
if (shouldStop) {
return res;
}
return currPromise().then((value) => {
if (value === "STOP") {
shouldStop = true;
} else {
res.push(value);
}
return res;
});
});
}, Promise.resolve([]));
final.then((resultant) => {
console.log(resultant);
});
async function runTasks(tasks) {
const results = [];
for (const task of tasks) {
const result = await task();
if (result === "STOP") {
break;
}
results.push(result);
}
return results;
}
runTasks(tasks).then((finalResults) => {
console.log(finalResults);
});
const limitTasks = [
() => new Promise((res) => setTimeout(() => res(1), 3000)),
() => new Promise((res) => setTimeout(() => res(2), 2000)),
() => new Promise((res) => setTimeout(() => res(3), 1000)),
() => new Promise((res) => setTimeout(() => res(4), 4000)),
() => new Promise((res) => setTimeout(() => res(5), 500)),
];
const limit = 2;
// This function takes an array of tasks and a concurrency limit
function parallelLimit(tasks, limit) {
// Keep track of total tasks and completion status
const totalTasks = tasks.length;
let taskCompleted = 0;
let runningTasks = 0;
const result = [];
// Return a promise that resolves when all tasks complete
return new Promise((resolve, reject) => {
// Helper function to execute a single task
const executeTask = (task) => {
// Return early if no task or at concurrency limit
if (!task) {
return;
}
if (runningTasks >= limit) {
return;
}
// Increment running tasks counter
runningTasks++;
// Execute the task and handle result
task()
.then((data) => {
// Store result and update counters
result.push(data);
runningTasks--;
taskCompleted++;
if (taskCompleted === totalTasks) {
// All tasks done - resolve with results
resolve(result);
} else {
// Start next task from queue
executeTask(tasks.shift());
}
})
.catch((error) => {
// Reject if any task fails
reject(error);
});
};
// Initially start up to 'limit' number of tasks
for (let i = 0; i < limit; i++) {
const task = tasks.shift();
executeTask(task);
}
});
}
parallelLimit(limitTasks, limit).then((res) => {
console.log(res);
});
const wait = (millis) => {
return new Promise((resolve) => {
setTimeout(() => resolve(), millis);
});
};
function promiseOrder(promises) {
let count = 0;
const result = new Array(promises.length);
return new Promise((resolve, reject) => {
for (const [index, task] of promises.entries()) {
task
.then(() => {
result[index] = count;
})
.catch((error) => {
reject(error);
})
.finally(() => {
count++;
if (count == promises.length) {
resolve(result);
}
});
}
});
}
promiseOrder([wait(100), wait(1000), wait(50)]).then((order) => {
console.log(order); // [1, 2, 0]
});
let attempt = 0;
function unstableFunction() {
return new Promise((resolve, reject) => {
attempt++;
if (attempt < 3) {
reject(`Failed attempt ${attempt}`);
} else {
resolve(`Success on attempt ${attempt}`);
}
});
}
function retries(fn, count) {
if (count == 0) {
return Promise.reject("Exceeded all retries");
}
return fn()
.then((value) => {
return Promise.resolve(value);
})
.catch(() => {
return retries(fn, count - 1);
});
}
retries(unstableFunction, 5)
.then((res) => {
console.log(res);
})
.catch((err) => {
console.error(err);
});