Skip to content

Commit

Permalink
feat(core/utils): add callUntilEnd, callPromiseUntilEnd
Browse files Browse the repository at this point in the history
  • Loading branch information
xiaodong2008 committed Oct 11, 2024
1 parent 4b90bb7 commit f5c60c1
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
47 changes: 47 additions & 0 deletions packages/core/src/utils/basic.ts
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);
});
}
3 changes: 3 additions & 0 deletions packages/core/src/utils/index.ts
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";

0 comments on commit f5c60c1

Please sign in to comment.