anki/ts/sveltelib/async.ts

28 lines
734 B
TypeScript
Raw Normal View History

import { Readable, readable } from "svelte/store";
2021-03-21 19:43:59 +01:00
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>;
loading: 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 loading = readable(true, (set: (value: boolean) => void) => {
2021-03-21 21:07:35 +01:00
promise.finally(() => set(false));
});
2021-03-21 19:43:59 +01:00
return { value, error, loading };
2021-03-21 19:43:59 +01:00
}
2021-03-21 21:07:35 +01:00
export default useAsync;