From 430d313be10102ae7623406afbe0eb8643f1fd53 Mon Sep 17 00:00:00 2001 From: Tom Hacohen Date: Sat, 8 Aug 2020 09:53:38 +0300 Subject: [PATCH] helpers: import some helpers from iOS. --- src/helpers.tsx | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) 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(() => {