Skip to content

Commit

Permalink
feat(useAsyncState): add support directly await (#3004)
Browse files Browse the repository at this point in the history
Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
  • Loading branch information
Hfutsora and antfu committed Apr 22, 2023
1 parent adbbb6e commit d4db0ad
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
7 changes: 7 additions & 0 deletions packages/core/useAsyncState/index.test.ts
Expand Up @@ -27,6 +27,13 @@ describe('useAsyncState', () => {
expect(state.value).toBe(2)
})

it('should work with await', async () => {
const asyncState = useAsyncState(p1, 0, { immediate: true })
expect(asyncState.isLoading.value).toBeTruthy()
await asyncState
expect(asyncState.isLoading.value).toBeFalsy()
})

it('should work with isLoading', () => {
const { execute, isLoading } = useAsyncState(p1, 0, { immediate: false })
expect(isLoading.value).toBeFalsy()
Expand Down
26 changes: 23 additions & 3 deletions packages/core/useAsyncState/index.ts
@@ -1,15 +1,19 @@
import { noop, promiseTimeout } from '@vueuse/shared'
import { noop, promiseTimeout, until } from '@vueuse/shared'
import type { Ref, UnwrapRef } from 'vue-demi'
import { ref, shallowRef } from 'vue-demi'

export interface UseAsyncStateReturn<Data, Params extends any[], Shallow extends boolean> {
export interface UseAsyncStateReturnBase<Data, Params extends any[], Shallow extends boolean> {
state: Shallow extends true ? Ref<Data> : Ref<UnwrapRef<Data>>
isReady: Ref<boolean>
isLoading: Ref<boolean>
error: Ref<unknown>
execute: (delay?: number, ...args: Params) => Promise<Data>
}

export type UseAsyncStateReturn<Data, Params extends any[], Shallow extends boolean> =
UseAsyncStateReturnBase<Data, Params, Shallow>
& PromiseLike<UseAsyncStateReturnBase<Data, Params, Shallow>>

export interface UseAsyncStateOptions<Shallow extends boolean, D = any> {
/**
* Delay for executing the promise. In milliseconds.
Expand Down Expand Up @@ -129,11 +133,27 @@ export function useAsyncState<Data, Params extends any[] = [], Shallow extends b
if (immediate)
execute(delay)

return {
const shell: UseAsyncStateReturnBase<Data, Params, Shallow> = {
state: state as Shallow extends true ? Ref<Data> : Ref<UnwrapRef<Data>>,
isReady,
isLoading,
error,
execute,
}

function waitUntilIsLoaded() {
return new Promise<UseAsyncStateReturnBase<Data, Params, Shallow>>((resolve, reject) => {
until(isLoading).toBe(false)
.then(() => resolve(shell))
.catch(reject)
})
}

return {
...shell,
then(onFulfilled, onRejected) {
return waitUntilIsLoaded()
.then(onFulfilled, onRejected)
},
}
}

0 comments on commit d4db0ad

Please sign in to comment.