Skip to content

Commit d4db0ad

Browse files
Hfutsoraantfu
andauthored
feat(useAsyncState): add support directly await (#3004)
Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
1 parent adbbb6e commit d4db0ad

File tree

2 files changed

+30
-3
lines changed

2 files changed

+30
-3
lines changed

packages/core/useAsyncState/index.test.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,13 @@ describe('useAsyncState', () => {
2727
expect(state.value).toBe(2)
2828
})
2929

30+
it('should work with await', async () => {
31+
const asyncState = useAsyncState(p1, 0, { immediate: true })
32+
expect(asyncState.isLoading.value).toBeTruthy()
33+
await asyncState
34+
expect(asyncState.isLoading.value).toBeFalsy()
35+
})
36+
3037
it('should work with isLoading', () => {
3138
const { execute, isLoading } = useAsyncState(p1, 0, { immediate: false })
3239
expect(isLoading.value).toBeFalsy()

packages/core/useAsyncState/index.ts

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,19 @@
1-
import { noop, promiseTimeout } from '@vueuse/shared'
1+
import { noop, promiseTimeout, until } from '@vueuse/shared'
22
import type { Ref, UnwrapRef } from 'vue-demi'
33
import { ref, shallowRef } from 'vue-demi'
44

5-
export interface UseAsyncStateReturn<Data, Params extends any[], Shallow extends boolean> {
5+
export interface UseAsyncStateReturnBase<Data, Params extends any[], Shallow extends boolean> {
66
state: Shallow extends true ? Ref<Data> : Ref<UnwrapRef<Data>>
77
isReady: Ref<boolean>
88
isLoading: Ref<boolean>
99
error: Ref<unknown>
1010
execute: (delay?: number, ...args: Params) => Promise<Data>
1111
}
1212

13+
export type UseAsyncStateReturn<Data, Params extends any[], Shallow extends boolean> =
14+
UseAsyncStateReturnBase<Data, Params, Shallow>
15+
& PromiseLike<UseAsyncStateReturnBase<Data, Params, Shallow>>
16+
1317
export interface UseAsyncStateOptions<Shallow extends boolean, D = any> {
1418
/**
1519
* Delay for executing the promise. In milliseconds.
@@ -129,11 +133,27 @@ export function useAsyncState<Data, Params extends any[] = [], Shallow extends b
129133
if (immediate)
130134
execute(delay)
131135

132-
return {
136+
const shell: UseAsyncStateReturnBase<Data, Params, Shallow> = {
133137
state: state as Shallow extends true ? Ref<Data> : Ref<UnwrapRef<Data>>,
134138
isReady,
135139
isLoading,
136140
error,
137141
execute,
138142
}
143+
144+
function waitUntilIsLoaded() {
145+
return new Promise<UseAsyncStateReturnBase<Data, Params, Shallow>>((resolve, reject) => {
146+
until(isLoading).toBe(false)
147+
.then(() => resolve(shell))
148+
.catch(reject)
149+
})
150+
}
151+
152+
return {
153+
...shell,
154+
then(onFulfilled, onRejected) {
155+
return waitUntilIsLoaded()
156+
.then(onFulfilled, onRejected)
157+
},
158+
}
139159
}

0 commit comments

Comments
 (0)