forked from DA0-DA0/dao-dao-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmisc.ts
37 lines (35 loc) · 1.38 KB
/
misc.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
/**
* Wrap a promise and give the caller the responsibility to resolve it after the
* promise succeeds.
*
* @param execute Async function to execute. If it throws an error, the promise
* will be rejected with the error. If it returns false, the promise returns
* immediately. Otherwise (if it does not return or returns true/undefined), it
* will be the caller's responsibility to resolve the promise using the resolve
* function passed into `onComplete`.
* @param onComplete Once the async function completes without error, this
* callback is called with the promise's resolve function, allowing the caller
* to manually trigger the resolve function when ready.
* @returns Promise that resolves when caller calls the resolve function, which
* is only possible after the async function completes.
*/
export const makeManuallyResolvedPromise =
<Params extends unknown[]>(
execute: (...args: Params) => Promise<boolean | undefined>,
onComplete: (resolve: () => void) => void
) =>
(...args: Params) =>
new Promise<void>(async (resolve, reject) => {
try {
const result = await execute(...args)
// If returns false, resolve immediately and return.
if (result === false) {
resolve()
return
}
// On completion, store resolve for later use.
onComplete(resolve)
} catch (err) {
reject(err)
}
})