anki/ts/sveltelib/async.ts
Damien Elmes b2049209ff Re-enable formatting for .ts files
There are some style differences compared to prettier, and not all are
necessarily an improvement, but it's much faster now.
2022-11-28 09:33:04 +10:00

32 lines
900 B
TypeScript

// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import type { Readable } from "svelte/store";
import { readable } from "svelte/store";
interface AsyncData<T, E> {
value: Readable<T | null>;
error: Readable<E | null>;
loading: Readable<boolean>;
}
function useAsync<T, E = unknown>(asyncFunction: () => Promise<T>): AsyncData<T, E> {
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 loading = readable(true, (set: (value: boolean) => void) => {
promise.finally(() => set(false));
});
return { value, error, loading };
}
export default useAsync;