diff --git a/src/helpers.tsx b/src/helpers.tsx index e8f5e3d..752e6eb 100644 --- a/src/helpers.tsx +++ b/src/helpers.tsx @@ -127,6 +127,34 @@ export function* arrayToChunkIterator(arr: T[], size: number) { } } +export function isPromise(x: any): x is Promise { + return x && typeof x.then === "function"; +} + +export function isDefined(x: T | undefined): x is T { + return x !== undefined; +} + +export function startTask(func: () => Promise | T, delay = 0): Promise { + return new Promise((resolve, reject) => { + setTimeout( + () => { + try { + const ret = func(); + if (isPromise(ret)) { + ret.then(resolve) + .catch(reject); + } else { + resolve(ret); + } + } catch (e) { + reject(e); + } + }, + delay); + }); +} + export function usePromiseMemo(promise: Promise | undefined | null, deps: React.DependencyList, initial: T | undefined = undefined): T | undefined { const [val, setVal] = React.useState((promise as any)._returnedValue ?? initial); React.useEffect(() => {