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

toPromise(actorRef) #4198

merged 22 commits into from
Dec 7, 2023

Conversation

davidkpiano
Copy link
Member

@davidkpiano davidkpiano commented Aug 20, 2023

This PR introduces toPromise(actor), which creates a promise from an actor that resolves with output when the actor is done.

import { createMachine, createActor, toPromise } from 'xstate';

const actor = createActor(createMachine({
  // ...
  states: {
    // ...
    done: { type: 'final', output: 42 }
  }
});

actor.start();

const output = await toPromise(actor);
// => 42

@davidkpiano davidkpiano requested a review from Andarist August 20, 2023 13:52
@changeset-bot
Copy link

changeset-bot bot commented Aug 20, 2023

🦋 Changeset detected

Latest commit: 6e35374

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
xstate Minor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@codesandbox-ci
Copy link

codesandbox-ci bot commented Aug 20, 2023

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

Latest deployment of this branch, based on commit 6e35374:

Sandbox Source
XState Example Template Configuration
XState React Template Configuration

@ghost
Copy link

ghost commented Aug 20, 2023

👇 Click on the image for a new way to code review

Review these changes using an interactive CodeSee Map

Legend

CodeSee Map legend

@Andarist
Copy link
Member

This supersedes #3977 , right? I certainly like this one better 😉

@Necmttn
Copy link

Necmttn commented Oct 17, 2023

Looking forward to this,
Currently, i have actor machines that execute in serverless environments.

const entryNode = di.editor.getNode(payload.workflowNodeId);
if (!entryNode) {
  throw new Error("Entry node not found");
}
let state = entryNode.actor.getSnapshot();
entryNode.actor.subscribe({
  next: (data) => {
    io.logger.info("STATE", data);
    state = data;
  },
  complete: () => {
    io.logger.log("COMPLETE", state.output);
  },
});
di.engine.execute(entryNode.id, undefined, payload.executionId);
await waitFor(entryNode.actor, (state) => state.matches("complete"), {
  timeout: 1000 * 60 * 5,
});
io.logger.info("STATE", state);

Currently, I'm using the waitFor method to wait for the actor to get the final state, but as API design wise this doesn't feel good to me.
another alternative of it kind a like this;

let state = entryNode.actor.getSnapshot();
await new Promise((resolve, reject) => {
  entryNode.actor.subscribe({
    error(err) {
      reject(err);
    },
    next: (data) => {
      io.logger.info("STATE", data);
      state = data;
    },
    complete: () => {
      resolve(state);
      io.logger.log("COMPLETE", state.output);
    },
  });
});

Which is also doesn't feel like the best.

@Andarist
Copy link
Member

This should be enough to "await" the actor with the v5 API:

await waitFor(actorRef, s => s.status === 'done')

We might still implement toPromise later on as a convenience but I don't feel like this one-liner is that bad even today.

@davidkpiano
Copy link
Member Author

This should be enough to "await" the actor with the v5 API:

await waitFor(actorRef, s => s.status === 'done')

We might still implement toPromise later on as a convenience but I don't feel like this one-liner is that bad even today.

For reference, this would be more than a one-liner unfortunately:

await waitFor(actorRef, s => s.status === 'done');
const output = actorRef.getSnapshot().output!;

@Andarist
Copy link
Member

Still a one-liner :P

const output = (await waitFor(actorRef, s => s.status === 'done')).output!;

@Andarist Andarist changed the base branch from next to main December 1, 2023 11:52
@Andarist Andarist changed the title [v5] toPromise(actor) toPromise(actorRef) Dec 7, 2023
export function toPromise<T extends AnyActorRef>(
actor: T
): Promise<OutputFrom<T>> {
// TODO: this is typed as `any`
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can't do much about it as long as we use T extends AnyActorRef pattern. You unwrap here what you provided for the TSnapshot within ActorRef but that's just any (since you are using AnyActorRef)

Comment on lines 35 to 37
if (currentSnapshot.status === 'error') {
return Promise.reject(currentSnapshot.error);
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Interestingly, this one is not redundant right now. I think this is a problem and I even thought that we had some tests related to this (although maybe indirect ones). I'll take a look at this right now.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe that we'll be able to remove this once this lands: #4570

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved ✅

@davidkpiano davidkpiano merged commit ca58904 into main Dec 7, 2023
2 checks passed
@davidkpiano davidkpiano deleted the v5/toPromise-1 branch December 7, 2023 18:05
@github-actions github-actions bot mentioned this pull request Dec 7, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants