Skip to content

Commit

Permalink
feat(useAsyncState): make useAsyncState thenable
Browse files Browse the repository at this point in the history
  • Loading branch information
Hfutsora committed Apr 21, 2023
1 parent b20aacf commit 2851571
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
7 changes: 7 additions & 0 deletions packages/core/useAsyncState/index.test.ts
Original file line number Diff line number Diff line change
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
22 changes: 19 additions & 3 deletions packages/core/useAsyncState/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
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'

Expand Down Expand Up @@ -78,7 +78,7 @@ export function useAsyncState<Data, Params extends any[] = [], Shallow extends b
promise: Promise<Data> | ((...args: Params) => Promise<Data>),
initialState: Data,
options?: UseAsyncStateOptions<Shallow, Data>,
): UseAsyncStateReturn<Data, Params, Shallow> {
): UseAsyncStateReturn<Data, Params, Shallow> & PromiseLike<UseAsyncStateReturn<Data, Params, Shallow>> {
const {
immediate = true,
delay = 0,
Expand Down Expand Up @@ -129,11 +129,27 @@ export function useAsyncState<Data, Params extends any[] = [], Shallow extends b
if (immediate)
execute(delay)

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

function waitUntilIsLoaded() {
return new Promise<UseAsyncStateReturn<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 2851571

Please sign in to comment.