Workflow.if() (experimental)
The .if()
method creates a conditional branch in the workflow, allowing steps to execute only when a specified condition is true. This enables dynamic workflow paths based on the results of previous steps.
Usage
workflow
.step(startStep)
.if(async ({ context }) => {
const value = context.getStepResult<{ value: number }>('start')?.value;
return value < 10; // If true, execute the "if" branch
})
.then(ifBranchStep)
.else()
.then(elseBranchStep)
.commit();
Parameters
condition:
Function | ReferenceCondition
A function or reference condition that determines whether to execute the 'if' branch
Condition Types
Function Condition
You can use a function that returns a boolean:
workflow
.step(startStep)
.if(async ({ context }) => {
const result = context.getStepResult<{ status: string }>('start');
return result?.status === 'success'; // Execute "if" branch when status is "success"
})
.then(successStep)
.else()
.then(failureStep);
Reference Condition
You can use a reference-based condition with comparison operators:
workflow
.step(startStep)
.if({
ref: { step: startStep, path: 'value' },
query: { $lt: 10 }, // Execute "if" branch when value is less than 10
})
.then(ifBranchStep)
.else()
.then(elseBranchStep);
Returns
workflow:
Workflow
The workflow instance for method chaining
Error Handling
The if
method requires a previous step to be defined. If you try to use it without a preceding step, an error will be thrown:
try {
// This will throw an error
workflow
.if(async ({ context }) => true)
.then(someStep)
.commit();
} catch (error) {
console.error(error); // "Condition requires a step to be executed after"
}