diff --git a/packages/core/src/utils/basic.ts b/packages/core/src/utils/basic.ts new file mode 100644 index 000000000..04991f3b7 --- /dev/null +++ b/packages/core/src/utils/basic.ts @@ -0,0 +1,47 @@ +import _dev from "../dev"; + +export async function callUntilEnd( + func: T extends true + ? (end: () => boolean) => Promise + : (end: () => boolean) => void | boolean, + timeout: number, + immediate: boolean = false, + promise: T = false as T +): Promise { + 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, + timeout: number = 1000, + immediate: boolean = false +): Promise { + return new Promise((resolve) => { + callUntilEnd(func, timeout, immediate, true).then(resolve); + }); +} diff --git a/packages/core/src/utils/index.ts b/packages/core/src/utils/index.ts index bfc3c486e..3fc29fe7a 100644 --- a/packages/core/src/utils/index.ts +++ b/packages/core/src/utils/index.ts @@ -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";