Using Sub-Workflows
IdentityFlow supports the concept of sub-workflows (or child workflows), allowing you to break down large, complex processes into smaller, more manageable, and often reusable units. A parent workflow can start one or more sub-workflows using flow.startWorkflow() and optionally wait for their completion or react to their outcomes.
Example: Order Fulfillment with Payment Sub-Workflow
export default defineWorkflow('order-fulfillment', async (flow) => { // Start a sub-workflow to handle payment processing // The parent workflow waits for the sub-workflow to complete const paymentResult = await flow.startWorkflow('process-payment', { params: { amount: flow.params.orderAmount, customerId: flow.params.customerId }, });
// Proceed based on the outcome of the sub-workflow if (paymentResult.status === 'paid') { await flow.startWorkflow('ship-order', { params: { orderId: flow.params.orderId, shippingAddress: flow.params.address }, }); return { overallStatus: 'Order Shipped' }; } else { // See Error Handling guide for more details flow.error('Payment failed for order', { orderId: flow.params.orderId, paymentStatus: paymentResult.status, }); // See [Error Handling](../10-error-handling/) return { overallStatus: 'Order Failed - Payment Issue' }; }});Benefits of Using Sub-Workflows:
- Modularity: Decompose complex logic into focused, understandable pieces.
- Reusability: Design generic sub-workflows (e.g., payment processing, notification sending) that can be invoked by multiple parent workflows.
- Isolation: Failures in a sub-workflow can be handled without necessarily halting the entire parent process, depending on your design.
- Scalability: Different teams can potentially own and develop different sub-workflows independently.
- Clarity: Parent workflows become easier to read as they orchestrate higher-level steps.
Sub-workflows are a key pattern for building sophisticated and maintainable automated processes.
Learn about Complex State Management for more advanced scenarios.