Skip to content

Commit

Permalink
fix async generator typing in flows
Browse files Browse the repository at this point in the history
  • Loading branch information
xaviergonz committed Oct 18, 2019
1 parent db3ddbd commit da478de
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
6 changes: 4 additions & 2 deletions src/api/flow.ts
Expand Up @@ -5,7 +5,7 @@ let generatorId = 0
export type CancellablePromise<T> = Promise<T> & { cancel(): void }

export function flow<R, Args extends any[]>(
generator: (...args: Args) => Generator<any, R, any>
generator: (...args: Args) => Generator<any, R, any> | AsyncGenerator<any, R, any>
): (...args: Args) => CancellablePromise<R> {
if (arguments.length !== 1)
fail(
Expand All @@ -18,7 +18,9 @@ export function flow<R, Args extends any[]>(
const ctx = this
const args = arguments
const runId = ++generatorId
const gen = action(`${name} - runid: ${runId} - init`, generator).apply(ctx, args)
const gen = action(`${name} - runid: ${runId} - init`, generator as (
...args: Args
) => Generator<any, R, any>).apply(ctx, args)
let rejector: (error: any) => void
let pendingPromise: CancellablePromise<any> | undefined = undefined

Expand Down
19 changes: 15 additions & 4 deletions test/base/typescript-tests.ts
Expand Up @@ -1557,9 +1557,9 @@ test("it should support asyncAction as decorator (ts)", async () => {
class X {
@observable a = 1

f = mobx.flow(function* f(initial: number): any {
f = mobx.flow(function* f(this: X, initial: number) {
this.a = initial // this runs in action
this.a += yield Promise.resolve(5)
this.a += yield Promise.resolve(5) as any
this.a = this.a * 2
return this.a
})
Expand Down Expand Up @@ -1590,7 +1590,7 @@ test("flow support async generators", async () => {
total += number
}
return total
} as any) // TODO: fix typings
})

const p = start()
const res = await p
Expand All @@ -1615,7 +1615,7 @@ test("flow support throwing async generators", async () => {
total += number
}
return total
} as any) // TODO: fix typings
})

const p = start()
try {
Expand Down Expand Up @@ -1647,3 +1647,14 @@ test("verify #1528", () => {

expect(appState.timer).toBe(0)
})

test("type of flows that return promises", async () => {
mobx.configure({ enforceActions: "observed" })

const f = mobx.flow(function* f() {
return Promise.resolve(5)
})

const n: number = await f()
expect(n).toBe(5)
})

0 comments on commit da478de

Please sign in to comment.