Repository navigation
Expand file tree
/
Copy pathpromiseWhile.ts
More file actions
51 lines (44 loc) · 1.55 KB
/
Copy pathpromiseWhile.ts
File metadata and controls
51 lines (44 loc) · 1.55 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
// eslint-disable-next-line lodash/import-scope
import type {DebouncedFunc} from 'lodash';
/**
* Simulates a while loop where the condition is determined by the result of a Promise.
*/
function promiseWhile(condition: () => boolean, action: (() => Promise<void>) | DebouncedFunc<() => Promise<void>> | undefined): Promise<void> {
return new Promise((resolve, reject) => {
const loop = function () {
if (!condition()) {
resolve();
} else {
const actionResult = action?.();
if (!actionResult) {
resolve();
return;
}
Promise.resolve(actionResult)
.then(() => {
// Set a timeout to delay the next loop iteration
setTimeout(loop, 1000); // 1000 ms delay
})
.catch(reject);
}
};
loop();
});
}
/**
* Simulates a do-while loop where the condition is determined by the result of a Promise.
*/
function promiseDoWhile(condition: () => boolean, action: (() => Promise<void>) | DebouncedFunc<() => Promise<void>> | undefined): Promise<void> {
return new Promise((resolve, reject) => {
const actionResult = action?.();
if (!actionResult) {
resolve();
return;
}
actionResult
.then(() => promiseWhile(condition, action))
.then(resolve)
.catch(reject);
});
}
export {promiseWhile, promiseDoWhile};