我在Node.JS后端使用xsate。以下是当前流程:
- 状态已重新水合(已初始化或从数据库中提取(
- 事件被发送到FSM
- 状态已序列化到数据库
这里有一些伪代码
const state = db.fetch(flowId) ?? machine.initialState;
// Use State.create() to restore state from a plain object
const previousState = State.create<DefaultContext, MyEvent>(stateDefinition);
// Use machine.resolveState() to resolve the state definition to a new State instance relative to the machine
const resolvedState = machine.resolveState(previousState);
const interpreter = interpret(machine).start(resolvedState);
onst newState: State<DefaultContext, MyEvent, any, Typestate<DefaultContext>> = interpreter.send(event);
db.saveState(flowId, newState);
我的问题是:有可能做出承诺吗?
我想保留我的FSM";"活着";如果我有悬而未决的承诺。目标是根据promise结果修改上下文。有什么钩子我可以用吗?
谢谢你的建议。
我有和您相同的用例。所以我要做的是在上下文中添加一个额外的属性,比如waitingAsync
。在状态条目中将其设置为true
,在完成时将其设置为false
。
遵循Invoking Promises示例进行一些修改:
// ...
loading: {
// set waitingAsync to true
entry: assign((context) => ({...context, waitingAsync: true})),
invoke: {
id: 'getUser',
src: (context, event) => fetchUser(context.userId),
onDone: {
target: 'success',
actions: [
assign({ user: (context, event) => event.data })
// set waitingAsync to false
assign((context) => ({...context, waitingAsync: false}))
]
},
}
},
// ...
然后,您可以使用waitFor帮助程序等待,直到完成承诺。
const interpreter = interpret(machine).start();
interpreter.send(event);
await waitFor(interpreter, (state) => !state.context.waitingAsync);
您现在可以在最新版本的XState中使用新的waitFor(...)
助手异步等待状态机达到某种条件,比如特定状态。
在您的情况下,谓词可能类似于state.matches('yourSuccessState')
。