From e1a80f56fd3bb96746a399072babfcdfbe2f33ae Mon Sep 17 00:00:00 2001 From: Thomas Reynolds Date: Tue, 14 Mar 2023 14:11:54 -0700 Subject: [PATCH] feat: actions bound to a runtime now return a Promise representing their completion (#717) BREAKING CHANGE: This is a type-only change --- src/__tests__/boundActions.spec.ts | 12 +++++++----- src/runtime.ts | 15 ++++++++++++--- src/svelte/createStore.ts | 7 ++++++- 3 files changed, 25 insertions(+), 9 deletions(-) diff --git a/src/__tests__/boundActions.spec.ts b/src/__tests__/boundActions.spec.ts index 21c56830..1ed5369e 100644 --- a/src/__tests__/boundActions.spec.ts +++ b/src/__tests__/boundActions.spec.ts @@ -37,15 +37,17 @@ describe("Bound actions", () => { const runtime = createRuntime(context, ["Add", "Multiply"]) + const boundActions = runtime.bindActions({ add, multiply }) + const onChange = jest.fn() runtime.onContextChange(onChange) await Promise.all([ - runtime.run(add(2)), - runtime.run(multiply(2)), - runtime.run(add(3)), - runtime.run(multiply(5)), - runtime.run(add(1)), + boundActions.add(2).asPromise(), + boundActions.multiply(2).asPromise(), + boundActions.add(3).asPromise(), + boundActions.multiply(5).asPromise(), + boundActions.add(1).asPromise(), ]) expect(runtime.currentState().data).toBe(36) diff --git a/src/runtime.ts b/src/runtime.ts index b3ad035f..d6aa2858 100644 --- a/src/runtime.ts +++ b/src/runtime.ts @@ -53,15 +53,24 @@ export class Runtime { bindActions< AM extends { [key: string]: (...args: Array) => Action }, - >(actions: AM): AM { + PM = { + [K in keyof AM]: (...args: Parameters) => { + asPromise: () => Promise + } + }, + >(actions: AM): PM { return Object.keys(actions).reduce((sum, key) => { sum[key] = (...args: Array) => { // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-non-null-assertion - return this.run(actions[key]!(...args)) + const promise = this.run(actions[key]!(...args)) + + return { + asPromise: () => promise, + } } return sum - }, {} as Record) as AM + }, {} as Record) as PM } async run(action: Action): Promise { diff --git a/src/svelte/createStore.ts b/src/svelte/createStore.ts index 33a1e79a..95709a07 100644 --- a/src/svelte/createStore.ts +++ b/src/svelte/createStore.ts @@ -7,10 +7,15 @@ import { Runtime, createRuntime } from "../runtime.js" export interface ContextValue< SM extends { [key: string]: BoundStateFn }, AM extends { [key: string]: (...args: Array) => Action }, + PM = { + [K in keyof AM]: (...args: Parameters) => { + asPromise: () => Promise + } + }, > { currentState: ReturnType context: Context - actions: AM + actions: PM runtime?: Runtime }