diff --git a/ts/graphs/async.ts b/ts/graphs/async.ts new file mode 100644 index 000000000..073ba42a9 --- /dev/null +++ b/ts/graphs/async.ts @@ -0,0 +1,28 @@ +import { Readable, readable, derived } from "svelte/store"; + +interface AsyncData { + value: Readable, + error: Readable, + pending: Readable, + successful: Readable, +} + + +function useAsync(asyncFunction: () => Promise): AsyncData { + const promise = asyncFunction(); + + const value = readable(null, (set: (value: T) => void) => { + promise.then((value: T) => set(value)) + }) + + const error = readable(null, (set: (value: E) => void) => { + promise.catch((value: E) => set(value)) + }) + + const pending = derived([value, error], (_, set) => set(true), true) + const successful = derived([value], (_, set) => set(true), false) + + return { value, error, pending, successful } +} + +export default useAsync