Skip to content

Commit

Permalink
feat(asyncComputed): onError option (vitest-dev#749)
Browse files Browse the repository at this point in the history
  • Loading branch information
wheatjs committed Sep 17, 2021
1 parent e557fa0 commit 706a049
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 8 deletions.
22 changes: 22 additions & 0 deletions packages/core/asyncComputed/index.test.ts
Expand Up @@ -35,6 +35,28 @@ describe('asyncComputed', () => {
expect(data.value).toBe('data')
})

it('call onError when error is thrown', async() => {
let errorMessage
const func = jest.fn(() => Promise.reject(new Error('An Error Message')))

const data = asyncComputed(func, undefined, {
onError(e) {
if (e instanceof Error)
errorMessage = e.message
},
})

expect(func).toBeCalledTimes(1)

expect(data.value).toBeUndefined()

await nextTick()
await nextTick()

expect(data.value).toBeUndefined()
expect(errorMessage).toBe('An Error Message')
})

it('is lazy if configured', async() => {
const func = jest.fn(() => Promise.resolve('data'))

Expand Down
28 changes: 20 additions & 8 deletions packages/core/asyncComputed/index.ts
@@ -1,4 +1,4 @@
import { Fn } from '@vueuse/shared'
import { Fn, noop } from '@vueuse/shared'
import { ref, isRef, computed, watchEffect, Ref } from 'vue-demi'

/**
Expand All @@ -8,15 +8,23 @@ import { ref, isRef, computed, watchEffect, Ref } from 'vue-demi'
*/
export type AsyncComputedOnCancel = (cancelCallback: Fn) => void

/**
* Additional options for asyncComputed
*
* @property lazy Should value be evaluated lazily
* @property evaluating Ref passed to receive the updated of async evaluation
*/
export type AsyncComputedOptions = {
export interface AsyncComputedOptions {
/**
* Should value be evaluated lazily
*
* @default false
*/
lazy?: Boolean

/**
* Ref passed to receive the updated of async evaluation
*/
evaluating?: Ref<boolean>

/**
* Callback when error is caught.
*/
onError?: (e: unknown) => void
}

/**
Expand Down Expand Up @@ -46,6 +54,7 @@ export function asyncComputed<T>(
const {
lazy = false,
evaluating = undefined,
onError = noop,
} = options

const started = ref(!lazy)
Expand Down Expand Up @@ -82,6 +91,9 @@ export function asyncComputed<T>(
if (counterAtBeginning === counter)
current.value = result
}
catch (e) {
onError(e)
}
finally {
if (evaluating)
evaluating.value = false
Expand Down

0 comments on commit 706a049

Please sign in to comment.