Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(useAsyncState): add support directly await #3004

Merged
merged 3 commits into from Apr 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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)
},
}
}