Skip to content

Commit fc29abe

Browse files
committed
fix: throw error on generator for sync too
1 parent 574b9a2 commit fc29abe

File tree

2 files changed

+18
-6
lines changed

2 files changed

+18
-6
lines changed

src/index.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,12 @@ function unwrapYield(value: any, isAsync?: boolean): any {
5959
function iterateSync<Return>(generator: QuansyncGenerator<Return, unknown>): Return {
6060
let current = generator.next()
6161
while (!current.done) {
62-
current = generator.next(unwrapYield(current.value))
62+
try {
63+
current = generator.next(unwrapYield(current.value))
64+
}
65+
catch (err) {
66+
current = generator.throw(err)
67+
}
6368
}
6469
return unwrapYield(current.value)
6570
}

test/index.test.ts

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -145,18 +145,25 @@ it('handle errors', async () => {
145145
},
146146
})
147147

148-
const fn = quansync(function* () {
148+
const returnError = quansync(function* (fn: () => any) {
149149
try {
150-
yield * throwError()
150+
yield * fn()
151151
}
152152
catch (err) {
153153
return err
154154
}
155155
})
156156

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]`)
157+
const fn = quansync(function* (fn: () => any) {
158+
return yield * fn()
159+
})
160+
161+
await expect(returnError(throwError)).resolves.toThrowErrorMatchingInlineSnapshot(`[Error: async error]`)
162+
await expect(returnError.async(throwError)).resolves.toThrowErrorMatchingInlineSnapshot(`[Error: async error]`)
163+
expect(returnError.sync(throwError)).toMatchInlineSnapshot(`[Error: sync error]`)
164+
165+
expect(returnError.sync(() => fn(throwError))).toMatchInlineSnapshot(`[Error: sync error]`)
166+
await expect(returnError.async(() => fn(throwError))).resolves.toMatchInlineSnapshot(`[Error: async error]`)
160167
})
161168

162169
it('yield generator', async () => {

0 commit comments

Comments
 (0)