-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsnippets-promises.js
116 lines (110 loc) · 2.91 KB
/
snippets-promises.js
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
/**
* Delay
*/
function delay(timeout) {
return new Promise(
(resolve) => {
const timeoutHandle =
setTimeout(() => {
clearTimeout(timeoutHandle);
resolve()
}, timeout);
});
}
// Example
async function example(){
console.log('The first log');
await delay(1000);
console.log('The second log with 1000 ms delay')
}
/**
* Break Up a Long-Running Task
*/
function nextFrame() {
const nextTick = requestAnimationFrame || setImmediate.
return new Promise((res) => nextTick(() => res()))
}
// Example usage
async function longRunningTask(){
let step = 0;
while(true){
if (++step % 5 === 0){
await nextFrame();
}
}
}
longRunningTask();
console.log('The first log')
/**
* Add a Timeout Limit To Promise
*/
function addTimeoutToPromise(targetPromise, timeout) {
let timeoutHandle;
const timeoutLimitPromise = new Promise((res, rej) => {
timeoutHandle = setTimeout(
() => rej(new Error('Timeout exceeded')),
timeout
);
});
return Promise.race([targetPromise, timeoutLimitPromise])
.then((res) => {
clearTimeout(timeoutHandle);
return res;
});
}
//Example: no timeout
addTimeoutToPromise(
delay(1000).then(() => console.log('Completed')), 2000
);
// --> Completed
// Example: timeout
addTimeoutToPromise(
delay(2000), 1000
).catch((e) => console.error(e.message))
// --> Timeout exceeded
/**
* Complete promises in sequence
*/
function completeInSequence(promiseFactories: () => Promise<any>) {
return promiseFactories.reduce(
(chain, promiseFactory) => chain.then(()=> promiseFactory()),
Promise.resolve()
);
}
// Example usage
completeInSequence([
() => delay(1000).then(() => console.log('1')),
() => delay(1000).then(() => console.log('2')),
() => delay(1000).then(() => console.log('3'))
])
/**
* Complete Only N Promises Simultaneously
*/
function completePromisesInPool(
promiseFactories: () => Promise<any>,
maxPoolSize: number
) {
return new Promise((res) => {
let nextPromise = 0;
const runPromise = () => {
nextPromise++;
if (nextPromise > promiseFactories.length) {
res();
return;
}
return promiseFactories[nextPromise-1]()
.then(() => runPromise())
}
Array.from({length: maxPoolSize})
.map(() => runPromise());
})
}
// Example usage
completePromisesInPool([
() => delay(1000).then(() => console.log('1')),
() => delay(1000).then(() => console.log('2')),
() => delay(1000).then(() => console.log('3')),
() => delay(1000).then(() => console.log('4')),
() => delay(1000).then(() => console.log('5')),
() => delay(1000).then(() => console.log('6'))
], 2)