anki/ts/graphs/async.ts

31 lines
853 B
TypeScript
Raw Normal View History

2021-03-21 19:43:59 +01:00
import { Readable, readable, derived } from "svelte/store";
2021-03-21 21:38:23 +01:00
interface AsyncData<T, E> {
2021-03-21 21:07:35 +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) => {
2021-03-21 21:07:35 +01:00
promise.then((value: T) => set(value));
});
2021-03-21 19:43:59 +01:00
const error = readable(null, (set: (value: E) => void) => {
2021-03-21 21:07:35 +01:00
promise.catch((value: E) => set(value));
});
const pending = readable(true, (set: (value: boolean) => void) => {
promise.finally(() => set(false));
});
2021-03-21 19:43:59 +01:00
2021-03-21 21:07:35 +01:00
const success = derived([value], (_, set) => set(true), false);
2021-03-21 19:43:59 +01:00
2021-03-21 21:07:35 +01:00
return { value, error, pending, success };
2021-03-21 19:43:59 +01:00
}
2021-03-21 21:07:35 +01:00
export default useAsync;