Skip to content

Commit

Permalink
feat(useAsyncState): execute is not async function
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Feb 27, 2021
1 parent d85250e commit f28591a
Showing 1 changed file with 19 additions and 22 deletions.
41 changes: 19 additions & 22 deletions packages/core/useAsyncState/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { noop } from '@vueuse/shared'
import { noop, promiseTimeout } from '@vueuse/shared'
import { ref, shallowRef } from 'vue-demi'

export interface AsyncStateOptions {
Expand Down Expand Up @@ -49,31 +49,28 @@ export function useAsyncState<T>(
const isReady = ref(false)
const error = ref<Error | undefined>(undefined)

function _run() {
const _promise = typeof promise === 'function'
? promise()
: promise

_promise
.then((data) => {
// @ts-ignore
state.value = data
isReady.value = true
})
.catch((e) => {
error.value = e
onError(e)
})
}

function execute(delay = 0) {
async function execute(delay = 0) {
state.value = initialState
error.value = undefined
isReady.value = false

if (!delay)
_run()
else
setTimeout(_run, delay)
await promiseTimeout(delay)

const _promise = typeof promise === 'function'
? promise()
: promise

try {
const data = await _promise
// @ts-ignore
state.value = data
isReady.value = true
}
catch (e) {
error.value = e
onError(e)
}
}

if (immediate)
Expand Down

0 comments on commit f28591a

Please sign in to comment.