Skip to content

Complex State Management

Workflows often involve managing complex states, conditional logic, and waiting for various external events or timeouts. IdentityFlow provides patterns to handle these scenarios effectively.

This example demonstrates an approval process that waits for an external response but also includes a timeout mechanism using Promise.race.

export default defineWorkflow('approval-process', async (flow) => {
const request = await flow.do('submit request', async () => {
return createRequest(flow.params); // Your function to create/submit the request
});
// Use Promise.race to wait for either an approval response or a timeout
const result = await Promise.race([
flow.request('approval response', async ({ token }) => {
// This step pauses the workflow, providing a token.
// An external system uses this token to send a response and resume the workflow.
return { requestId: request.id, token };
}),
flow.sleep('escalation timeout', '48 hours', { timedOut: true }), // If sleep resolves first, it's a timeout
]);
if (result.timedOut) {
// Check if the timeout occurred
return flow.do('handle timeout', async () => {
return handleEscalation(request.id); // Your escalation logic
});
}
// If not a timeout, 'result' will be the data sent from the external system
// (assuming the external system sends an object with a 'status' field)
if (result.status === 'approved') {
return flow.do('process approval', async () => {
return processApproval(request.id); // Your approval logic
});
}
return flow.do('handle rejection', async () => {
return handleRejection(request.id, result.reason); // Your rejection logic
});
});

Key Techniques:

  • flow.request(): Pause a workflow to wait for external input, providing a token for correlation.
  • flow.sleep(): Introduce delays or implement timeouts.
  • Promise.race(): Manage competing events, such as an external response versus a timeout.
  • Promise.all() / Promise.allSettled(): Handle parallel execution of steps within a stage. See Parallel Processing.
  • Conditional Logic**: Standard JavaScript if/else or switch statements to direct flow based on data or step outcomes.

By combining these patterns, you can model sophisticated stateful interactions within your IdentityFlow workflows.

Explore Custom Step Types for more reusable logic.