-
Notifications
You must be signed in to change notification settings - Fork 0
/
promiseWait.ts
52 lines (48 loc) · 1.62 KB
/
promiseWait.ts
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
/**
* Produce Promise during for "no less than pointed time".
* If Promise takes more than pointed time: no additional waiting
* If Promise resolves or rejects in less than pointed time: waiting for rest time
* @param promise Promise that we must wait for pointed time
* @param ms min time that Promise must take
* @param [smartOrCallback=true] Allow not to wait if pointed promise is resolved immediately default-`true`
* @example
* let isPending = false
* promiseWait(Promise.resolve(), 300, (isWait) => (isPending=isWait))
* // OR
* isPending = true;
* promiseWait(Promise.resolve(), 300, true).finally(() => (isPending=false)) */
export default function promiseWait<T>(
promise: Promise<T>,
ms: number,
smartOrCallback: boolean | ((isWait: boolean) => any) = true
): Promise<T> {
let catchErr: Error;
let isResolved = false;
let resCnt = 0;
let back: boolean;
promise
.catch((err) => (catchErr = err)) //
.finally(() => {
isResolved = true;
++resCnt === 2 && back && (smartOrCallback as Func)(false);
});
const p = new Promise((res, rej) => {
const end = (): void => {
++resCnt === 2 && back && (smartOrCallback as Func)(false);
catchErr ? rej(catchErr) : res(promise);
};
const a = setTimeout(end, ms);
smartOrCallback &&
setTimeout(() => {
if (isResolved) {
clearTimeout(a);
end();
} else if (typeof smartOrCallback === "function") {
smartOrCallback(true);
back = true;
// p.finally(() => smartOrCallback(false)); // .catch(() => null);
}
});
});
return p as Promise<T>;
}