anki/ts/graphs/async.ts

29 lines
803 B
TypeScript
Raw Normal View History

2021-03-21 19:43:59 +01:00
import { Readable, readable, derived } from "svelte/store";
export interface AsyncData<T, E> {
2021-03-21 19:43:59 +01:00
value: Readable<T | null>,
error: Readable<E | null>,
pending: Readable<boolean>,
success: Readable<boolean>,
2021-03-21 19:43:59 +01:00
}
function useAsync<T, E = unknown>(asyncFunction: () => Promise<T>): AsyncData<T, E> {
2021-03-21 19:43:59 +01:00
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(false), true)
const success= derived([value], (_, set) => set(true), false)
2021-03-21 19:43:59 +01:00
return { value, error, pending, success }
2021-03-21 19:43:59 +01:00
}
export default useAsync