Skip to content

Commit 0e189de

Browse files
committed
fix: throw error on generator
1 parent 1c8f08d commit 0e189de

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

src/index.ts

+6-1
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,12 @@ function iterateSync<Return>(generator: QuansyncGenerator<Return, unknown>): Ret
6767
async function iterateAsync<Return>(generator: QuansyncGenerator<Return, unknown>): Promise<Return> {
6868
let current = generator.next()
6969
while (!current.done) {
70-
current = generator.next(await unwrapYield(current.value, true))
70+
try {
71+
current = generator.next(await unwrapYield(current.value, true))
72+
}
73+
catch (err) {
74+
current = generator.throw(err)
75+
}
7176
}
7277
return current.value
7378
}

test/index.test.ts

+26-1
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ it('yield promise', async () => {
118118
await expect(run.async('foo')).resolves.toBe('foo')
119119
})
120120

121-
it('handle errors', async () => {
121+
it('throw errors', async () => {
122122
const throwError = quansync({
123123
name: 'throwError',
124124
sync: () => {
@@ -134,6 +134,31 @@ it('handle errors', async () => {
134134
expect(() => throwError.sync()).toThrowErrorMatchingInlineSnapshot(`[Error: sync error]`)
135135
})
136136

137+
it('handle errors', async () => {
138+
const throwError = quansync({
139+
name: 'throwError',
140+
sync: () => {
141+
throw new Error('sync error')
142+
},
143+
async: async () => {
144+
return Promise.reject(new Error('async error'))
145+
},
146+
})
147+
148+
const fn = quansync(function* () {
149+
try {
150+
yield * throwError()
151+
}
152+
catch (err) {
153+
return err
154+
}
155+
})
156+
157+
await expect(fn()).resolves.toThrowErrorMatchingInlineSnapshot(`[Error: async error]`)
158+
await expect(fn.async()).resolves.toThrowErrorMatchingInlineSnapshot(`[Error: async error]`)
159+
expect(fn.sync()).toMatchInlineSnapshot(`[Error: sync error]`)
160+
})
161+
137162
it('yield generator', async () => {
138163
const toString = quansync({
139164
name: 'toString',

0 commit comments

Comments
 (0)