If-Else Control Node
Overview
The If-Else control node is a core control flow component in the workflow system that allows you to select different execution paths based on the result of a condition expression. When the condition evaluates to true, the true branch is executed; when it evaluates to false, the false branch is executed. This branching control mechanism is the foundation for building complex business logic.
Core Features
- ✅ Condition Evaluation: Supports complex JavaScript condition expressions
- ✅ Secure Execution: Evaluates conditions in an isolated VM sandbox environment
- ✅ Data Flow Passing: Automatically passes output data from upstream nodes
- ✅ Dynamic Branching: Dynamically creates and executes sub-workflows based on condition results
- ✅ Type Support: Supports comparison of numbers, strings, booleans, and objects
Node Configuration
Basic Configuration Structure
{
"type": "control",
"config": {
"identifier": "if_else",
"name": "Condition Check Node"
},
"metadata": {
"origin": "built-in",
"runtime": { "type": "worker" }
}
}
Configuration Parameter Reference
| Parameter | Type | Required | Description |
|---|---|---|---|
type | string | ✅ | Node type, fixed as "control" |
config.identifier | string | ✅ | Control node identifier, fixed as "if_else" |
config.name | string | ❌ | Display name of the node |
Input and Output Ports
Input Ports
| Port Name | Type | Required | Description |
|---|---|---|---|
data | any | ✅ | Data for condition evaluation, typically from upstream nodes |
condition | string | ✅ | Condition expression (JavaScript syntax) |
Output Ports
| Port Name | Type | Description |
|---|---|---|
true | any | Data output when the condition is true |
false | any | Data output when the condition is false |
Condition Expression Syntax
The If-Else node uses JavaScript syntax to write condition expressions, which are executed in a secure VM sandbox environment.
Basic Syntax
The following variables and objects are available within condition expressions:
data: The input data objectinputs: The complete input objectcontext: The workflow execution contextMath: The Math calculation objectDate: The Date handling objectutils: A collection of utility functions
Supported Operators
// Comparison operators
data.age > 18 // Greater than
data.score >= 90 // Greater than or equal to
data.name === "Alice" // Strict equality
data.status !== "inactive" // Not equal to
// Logical operators
data.age > 18 && data.verified === true // Logical AND
data.type === "VIP" || data.score > 95 // Logical OR
!(data.blocked === true) // Logical NOT
// Type checking
typeof data.name === "string"
Array.isArray(data.items)
data.date instanceof Date
// String operations
data.email.includes("@example.com")
data.name.startsWith("Admin")
data.status.toLowerCase() === "active"
Utility Functions
Built-in utility functions are available within condition expressions:
// Type checking
utils.isString(data.name)
utils.isNumber(data.age)
utils.isEmpty(data.description)
// Validation functions
utils.isEmail(data.email)
utils.isURL(data.website)
Edge Connection Configuration
Data Input Edge
Pass data from an upstream node to the If-Else node:
{
"source": "data-processor:result",
"target": "condition-check:data",
"dataPath": ""
}
Condition Branch Edges
Pass results from the If-Else node to downstream nodes:
// True branch
{
"source": "condition-check:true",
"target": "success-handler:parameters",
"dataPath": ""
}
// False branch
{
"source": "condition-check:false",
"target": "failure-handler:parameters",
"dataPath": ""
}
Complete Examples
Example 1: User Age Verification
This example demonstrates how to verify a user's age and execute different processing logic based on the result.
Workflow Configuration
{
"nodes": {
"user-data-processor": {
"type": "operator",
"config": {
"identifier": "js-executor",
"name": "User Data Processor"
}
},
"age-verification": {
"type": "control",
"config": {
"identifier": "if_else",
"name": "Age Verification"
}
},
"adult-handler": {
"type": "operator",
"config": {
"identifier": "js-executor",
"name": "Adult Handler"
}
},
"minor-handler": {
"type": "operator",
"config": {
"identifier": "js-executor",
"name": "Minor Handler"
}
}
},
"edges": [
{
"source": "user-data-processor:result",
"target": "age-verification:data"
},
{
"source": "age-verification:true",
"target": "adult-handler:parameters"
},
{
"source": "age-verification:false",
"target": "minor-handler:parameters"
}
]
}
Node Input Data
{
"user-data-processor": {
"code": "const user = { name: 'Alice', age: 25, email: 'alice@example.com' }; return user;",
"parameters": {}
},
"age-verification": {
"condition": "data.age >= 18"
},
"adult-handler": {
"code": "return { status: 'approved', message: `Welcome ${params.name}! You have passed the age verification.`, userInfo: params };",
"parameters": {}
},
"minor-handler": {
"code": "return { status: 'rejected', message: `Sorry ${params.name}, you do not meet the age requirement.`, userInfo: params };",
"parameters": {}
}
}
Execution Result
When the user's age is 25:
- The condition
data.age >= 18evaluates totrue - The
adult-handlernode is executed - An approval message is returned
Example 2: Exam Score Grading
This example demonstrates how to assign grades based on exam scores.
Condition Configuration
{
"condition": "data.score >= 90 && data.score <= data.maxScore"
}
Data Processing
// Input data processing
const exam = {
student: 'Charlie',
subject: 'Math',
score: 92,
maxScore: 100
};
// Condition evaluation: 92 >= 90 && 92 <= 100 → true
// Execute the excellent grade processing logic
Example 3: Complex Business Conditions
// Multi-condition combination
data.userType === "VIP" && data.orderAmount > 1000 && data.region === "premium"
// Nested property evaluation
data.profile && data.profile.verified === true && data.profile.level > 3
// Array and string operations
data.tags.includes("priority") || data.email.endsWith("@company.com")
Data Flow Processing
Data Passing Mechanism
- Upstream Data Collection: The If-Else node collects output data from connected upstream nodes
- Condition Evaluation: The condition expression is executed in a secure sandbox
- Branch Selection: The true or false branch is selected based on the condition result
- Data Passing: The original input data is passed to the selected branch node
Data Flow Diagram
┌─────────────────┐ data ┌─────────────┐
│ Data Processor │ ─────────► │ If-Else │
└─────────────────┘ │ Node │
└─────┬───┬───┘
│ │
true │ │ false
▼ ▼
┌─────────┐ ┌─────────┐
│ Success │ │ Failure │
│ Handler │ │ Handler │
└─────────┘ └─────────┘
Best Practices
1. Condition Expression Design
// ✅ Recommended: Clear condition expressions
data.age >= 18 && data.verified === true
// ❌ Avoid: Overly complex conditions
data.age >= 18 && data.verified === true && data.profile && data.profile.settings && data.profile.settings.notifications === "enabled"
// ✅ Recommended: Simplify using utility functions
utils.isNumber(data.age) && data.age >= 18
2. Error Handling
// ✅ Safe property access
data && data.user && data.user.age > 18
// ✅ Type checking
typeof data.score === "number" && data.score >= 60
3. Performance Optimization
- Avoid performing complex calculations within condition expressions
- Check simpler conditions first and leverage short-circuit evaluation
- Use utility functions for common validations
4. Debugging Tips
Enable debug mode to view the condition evaluation process:
// The condition evaluation log will display:
// - Input data content
// - Condition expression text
// - Evaluation result (true/false)
// - Selected execution branch
Security Features
VM Sandbox Isolation
The If-Else node executes condition evaluation in an isolated VM environment, ensuring:
- ✅ No access to system resources
- ✅ No execution of dangerous operations
- ✅ No modification of global state
- ✅ Automatic timeout protection (5 seconds)
Security Restrictions
The following operations are prohibited in condition expressions:
// ❌ Prohibited operations
require("fs") // Module imports
eval("malicious code") // Code execution
process.exit() // System calls
global.something = value // Global variable modification
Troubleshooting
Common Issues
1. Condition Always Evaluates to False
Symptom: The condition always evaluates to false regardless of input data
Causes:
- Data passing configuration error
- Syntax error in the condition expression
- Data type mismatch
Solution:
// Check if data is correctly passed
console.log("Input data:", data);
// Verify data type
typeof data.age === "number"
// Use safe access
data && data.age && data.age > 18
2. Branch Not Executed
Symptom: The If-Else node works correctly, but downstream branch nodes are not executed
Causes:
- Edge connection configuration error
- Node identifier mismatch
- Data path configuration issue
Solution:
- Check the source and target configuration of edges
- Confirm that node IDs are correct
- Verify data path expressions
3. Performance Issues
Symptom: Condition evaluation takes too long
Causes:
- Overly complex condition expression
- Input data volume is too large
- Recursive or looping operations
Solution:
- Simplify the condition expression
- Pre-process data in upstream nodes
- Avoid heavy computations within conditions
Debugging Tools
Enable verbose logging to view the execution process:
{
"condition": "data.age > 18",
"debug": true
}
Debug output example:
Condition evaluation started: data.age > 18
Input data: { name: "Alice", age: 25 }
Evaluation result: true
Selected branch: true
Advanced Usage
Condition Chains
Multiple If-Else nodes can be chained together to implement complex conditional logic:
Input → Age Check → Adult Check → VIP Check → Final Handler
↓ ↓ ↓
Minor Handler Regular Standard
Dynamic Conditions
Condition expressions can reference dynamic values in the context:
// Reference a configuration value in the context
data.score >= context.passingScore
// Use date comparison
new Date(data.timestamp) > new Date("2024-01-01")
Related Documentation
- Workflow Overview — Workflow engine fundamentals
- Context Management — Workflow context and data passing
- ForEach Loop Node — Loop control node
- Switch Branch Node — Multi-branch control node