DocsReferenceWorkflowsReference: Workflow.else() | Conditional Branching | Mastra Docs

Workflow.else() (experimental)

The .else() method creates an alternative branch in the workflow that executes when the preceding if condition evaluates to false. This enables workflows to follow different paths based on conditions.

Usage

workflow
  .step(startStep)
  .if(async ({ context }) => {
    const value = context.getStepResult<{ value: number }>('start')?.value;
    return value < 10;
  })
  .then(ifBranchStep)
  .else() // Alternative branch when the condition is false
  .then(elseBranchStep)
  .commit();

Parameters

The else() method does not take any parameters.

Returns

workflow:

Workflow
The workflow instance for method chaining

Behavior

  • The else() method must follow an if() branch in the workflow definition
  • It creates a branch that executes only when the preceding if condition evaluates to false
  • You can chain multiple steps after an else() using .then()
  • You can nest additional if/else conditions within an else branch

Error Handling

The else() method requires a preceding if() statement. If you try to use it without a preceding if, an error will be thrown:

try {
  // This will throw an error
  workflow
    .step(someStep)
    .else()
    .then(anotherStep)
    .commit();
} catch (error) {
  console.error(error); // "No active condition found"
}