Skip to content

Instantly share code, notes, and snippets.

@jamestharpe
Created December 5, 2021 01:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamestharpe/7b30c8b07966db46cb5b5a13afea86bb to your computer and use it in GitHub Desktop.
Save jamestharpe/7b30c8b07966db46cb5b5a13afea86bb to your computer and use it in GitHub Desktop.
/* eslint-disable @typescript-eslint/no-explicit-any */
import { createMachine, interpret, Interpreter, State } from "xstate";
const promiseMachine = createMachine({
id: "promise",
initial: "pending",
states: {
pending: {
on: {
RESOLVE: { target: "resolved" },
REJECT: { target: "rejected" },
},
},
resolved: {
type: "final",
},
rejected: {
type: "final",
},
},
});
const waitUntil = <TState extends State<any>>(
interpreter: Interpreter<any>,
condition: (state: TState) => boolean
): Promise<TState> => {
console.log("Waiting...");
return new Promise((resolve) => {
const listener = (state: TState) => {
console.log("Checking state", state.toStrings());
if (condition(state)) {
console.log("Condition met!");
interpreter.off(listener);
resolve(state);
}
};
interpreter.onTransition(listener as any);
});
};
const somePromise = interpret(promiseMachine)
.onTransition((state) => console.log("Transitioned to", state.toStrings()))
.start();
waitUntil(somePromise, (state) => state.matches("resolved")).then((state) =>
console.log("Resolved!", state.toStrings())
);
waitUntil(somePromise, (state) => Boolean(state.done)).then((state) => console.log("Done!", state.toStrings()));
console.log("Resolving", somePromise.send("RESOLVE").toStrings(), somePromise.state.toStrings());
@jamestharpe
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment