Skip to content

Commit 450a8a8

Browse files
authored
fix(reactivity): preserve watch callback return value when wrapped for once: true (#14902)
1 parent 48ad452 commit 450a8a8

2 files changed

Lines changed: 43 additions & 1 deletion

File tree

‎packages/reactivity/__tests__/watch.spec.ts‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,47 @@ describe('watch', () => {
116116
])
117117
})
118118

119+
test('call option with async error handling', async () => {
120+
const onError = vi.fn()
121+
const call: WatchOptions['call'] = function call(fn, type, args) {
122+
if (Array.isArray(fn)) {
123+
fn.forEach(f => call(f, type, args))
124+
return
125+
}
126+
fn.apply(null, args).catch((error: unknown) => {
127+
onError(error)
128+
})
129+
}
130+
131+
const source1 = ref(0)
132+
watch(
133+
source1,
134+
async () => {
135+
throw 'oops in watch'
136+
},
137+
{ call },
138+
)
139+
140+
source1.value++
141+
await nextTick()
142+
expect(onError.mock.calls.length).toBe(1)
143+
expect(onError.mock.calls[0]).toMatchObject(['oops in watch'])
144+
145+
const source2 = ref(0)
146+
watch(
147+
source2,
148+
async () => {
149+
throw 'oops in once watch'
150+
},
151+
{ call, once: true },
152+
)
153+
154+
source2.value++
155+
await nextTick()
156+
expect(onError.mock.calls.length).toBe(2)
157+
expect(onError.mock.calls[1]).toMatchObject(['oops in once watch'])
158+
})
159+
119160
test('watch with onWatcherCleanup', async () => {
120161
let dummy = 0
121162
let source: Ref<number>

‎packages/reactivity/src/watch.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -221,8 +221,9 @@ export function watch(
221221
if (once && cb) {
222222
const _cb = cb
223223
cb = (...args) => {
224-
_cb(...args)
224+
const res = _cb(...args)
225225
watchHandle()
226+
return res
226227
}
227228
}
228229

0 commit comments

Comments
 (0)