Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

toPromise(actorRef) #4198

Merged
merged 22 commits into from
Dec 7, 2023
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion docs/about/goals.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,4 @@ If you're deciding if you should use XState, [John Yanarella](https://github.com
> The front-end development world is the wild west, and it could stand to learn from what other engineering disciplines have known and employed for years.
>
> 3. It has **passed a critical threshold of maturity** as of version 4, particularly given the introduction of [the visualizer](https://statecharts.github.io/xstate-viz). And that's just the tip of the iceberg of where it could go next, as it (and [its community](https://github.com/statelyai/xstate/discussions)) introduces tooling that takes advantage of how a statechart can be visualized, analyzed, and tested.
>
> 4. The **community** that is growing around it and the awareness it is bringing to finite state machines and statecharts. If you read back through this gitter history, there's a wealth of links to research papers, other FSM and Statechart implementations, etc. that have been collected by [Erik Mogensen](https://twitter.com/mogsie) over at [statecharts.github.io](https://statecharts.github.io).
31 changes: 17 additions & 14 deletions docs/recipes/svelte.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,19 +59,21 @@ export const toggleMachine = createMachine({

```html
<script>
import {interpret} from 'xstate';
import {toggleMachine} from './machine';
import { interpret } from 'xstate';
import { toggleMachine } from './machine';

let current;
let current;

const toggleService = interpret(toggleMachine)
.onTransition((state) => {
current = state;
}).start()
const toggleService = interpret(toggleMachine)
.onTransition((state) => {
current = state;
})
.start();
</script>

<button on:click={() => toggleService.send({ type: 'TOGGLE' })}>
{current.matches('inactive') ? 'Off' : 'On'}
<button on:click="{()" ="">
toggleService.send({ type: 'TOGGLE' })}> {current.matches('inactive') ? 'Off'
: 'On'}
</button>
```

Expand All @@ -81,14 +83,15 @@ The toggleService has a `.subscribe` function that is similar to Svelte stores,

```html
<script>
import {interpret} from 'xstate';
import {toggleMachine} from './machine';
import { interpret } from 'xstate';
import { toggleMachine } from './machine';

const toggleService = interpret(toggleMachine).start();
const toggleService = interpret(toggleMachine).start();
</script>

<button on:click={() => toggleService.send({ type: 'TOGGLE' })}>
{$toggleService.matches('inactive') ? 'Off' : 'On'}
<button on:click="{()" ="">
toggleService.send({ type: 'TOGGLE' })}> {$toggleService.matches('inactive') ?
'Off' : 'On'}
</button>
```

Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export type {
InspectedSnapshotEvent,
InspectionEvent
} from './system.ts';

export { toPromise } from './toPromise.ts';
export { and, not, or, stateIn } from './guards.ts';
export { setup } from './setup.ts';

Expand Down
1 change: 1 addition & 0 deletions packages/core/src/interpreter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import type {
EventFromLogic,
SnapshotFrom,
AnyActorRef,
OutputFrom,
DoneActorEvent,
Snapshot
} from './types.ts';
Expand Down
21 changes: 21 additions & 0 deletions packages/core/src/toPromise.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Actor, ActorRef, AnyActor, AnyActorRef, OutputFrom } from '.';

export function toPromise<T extends AnyActorRef>(
actor: T
): Promise<T extends Actor<infer TLogic> ? OutputFrom<TLogic> : unknown> {
return new Promise((resolve, reject) => {
actor.subscribe({
complete: () => {
resolve(
actor.getSnapshot().output
// actor.getOutput()! as T extends Actor<infer TLogic>
// ? OutputFrom<TLogic>
// : unknown
);
},
error: (err) => {
reject(err);
}
});
});
}
76 changes: 76 additions & 0 deletions packages/core/test/toPromise.test.ts
davidkpiano marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import {
ActorRef,
createActor,
createMachine,
fromPromise,
toPromise
} from '../src';

describe('toPromise', () => {
it('should be awaitable', async () => {
const promiseActor = createActor(
fromPromise(() => Promise.resolve(42))
).start();

const result = await toPromise(promiseActor);

((_accept: number) => {})(result);
davidkpiano marked this conversation as resolved.
Show resolved Hide resolved

expect(result).toEqual(42);
});

it('should await actors', async () => {
const machine = createMachine({
types: {} as {
output: { count: 42 };
},
initial: 'pending',
states: {
pending: {
on: {
RESOLVE: 'done'
}
},
done: {
type: 'final'
}
},
output: { count: 42 }
});

const actor = createActor(machine).start();

setTimeout(() => {
actor.send({ type: 'RESOLVE' });
}, 1);

const data = await toPromise(actor);

((_accept: { count: number }) => {})(data);

expect(data).toEqual({ count: 42 });
});

it('should await already done actors', async () => {
const machine = createMachine({
types: {} as {
output: { count: 42 };
},
initial: 'done',
states: {
done: {
type: 'final'
}
},
output: { count: 42 }
});

const actor = createActor(machine).start();

const data = await toPromise(actor);

((_accept: { count: number }) => {})(data);

expect(data).toEqual({ count: 42 });
});
});