-
-
Notifications
You must be signed in to change notification settings - Fork 40
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(core/utils): add callUntilEnd, callPromiseUntilEnd
- Loading branch information
1 parent
4b90bb7
commit f5c60c1
Showing
2 changed files
with
50 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
import _dev from "../dev"; | ||
|
||
export async function callUntilEnd<T extends boolean>( | ||
func: T extends true | ||
? (end: () => boolean) => Promise<void | boolean> | ||
: (end: () => boolean) => void | boolean, | ||
timeout: number, | ||
immediate: boolean = false, | ||
promise: T = false as T | ||
): Promise<void> { | ||
return new Promise((resolve, reject) => { | ||
let end = false; | ||
const endFunc = () => end; | ||
|
||
setTimeout(callFunc, immediate ? 0 : timeout); | ||
|
||
async function callFunc() { | ||
try { | ||
end = promise ? !!(await func(endFunc)) : !!func(endFunc); | ||
// Don't use else, using else can't detect is endFunc called, it can only detect is func returns true | ||
if (!end) { | ||
setTimeout(callFunc, timeout); | ||
} else resolve(); | ||
} catch (error: any) { | ||
if (__DEV__) { | ||
_dev.warn( | ||
"fastjs/utils/doUntilEnd", | ||
"An error occurred while executing the function", | ||
error | ||
); | ||
} | ||
reject(error); | ||
end = true; | ||
} | ||
} | ||
}); | ||
} | ||
|
||
export function callPromiseUntilEnd( | ||
func: (end: () => boolean) => Promise<void | boolean>, | ||
timeout: number = 1000, | ||
immediate: boolean = false | ||
): Promise<void> { | ||
return new Promise((resolve) => { | ||
callUntilEnd(func, timeout, immediate, true).then(resolve); | ||
}); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,9 +1,12 @@ | ||
import * as basic from "./basic"; | ||
import * as dom from "./dom"; | ||
import * as rand from "./rand"; | ||
|
||
export default { | ||
...basic, | ||
...dom, | ||
...rand | ||
}; | ||
export * from "./dom"; | ||
export * from "./rand"; | ||
export * from "./basic"; |