mirror of
https://github.com/ankitects/anki.git
synced 2025-09-18 22:12:21 -04:00
Add Svelte async hook
This commit is contained in:
parent
f08c5a9905
commit
f82a02bd2e
1 changed files with 28 additions and 0 deletions
28
ts/graphs/async.ts
Normal file
28
ts/graphs/async.ts
Normal file
|
@ -0,0 +1,28 @@
|
|||
import { Readable, readable, derived } from "svelte/store";
|
||||
|
||||
interface AsyncData<T, E> {
|
||||
value: Readable<T | null>,
|
||||
error: Readable<E | null>,
|
||||
pending: Readable<boolean>,
|
||||
successful: Readable<boolean>,
|
||||
}
|
||||
|
||||
|
||||
function useAsync<T, E = Error>(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 pending = derived([value, error], (_, set) => set(true), true)
|
||||
const successful = derived([value], (_, set) => set(true), false)
|
||||
|
||||
return { value, error, pending, successful }
|
||||
}
|
||||
|
||||
export default useAsync
|
Loading…
Reference in a new issue