Loop Node

The Loop node iterates through arrays, processes collections, and repeats operations with AI assistance to help generate complex iteration logic.

Overview

Loop nodes enable:

  • Array iteration (for-each)
  • Fixed repetition (for loop)
  • Conditional loops (while)
  • Batch processing
  • Parallel iteration options

✨ AI Loop Wizard

The Loop node features AI assistance for complex iterations:

Using the AI Wizard

  1. Click the sparkles (✨) button in configuration
  2. Describe your iteration need:
    • "Process each customer and calculate their total"
    • "Retry up to 5 times until success"
    • "Group items by category and sum values"
  3. AI configures the loop automatically
  4. **Review

and customize** as needed

AI Wizard Examples

"Process orders in batches of 10" → Configures batch processing

"Filter and transform active users" → Sets up filtering iteration

"Retry failed API calls with backoff" → Creates retry loop with delays

Configuration

Loop Types

For Each (Array Iteration)

Most common - processes each item in an array:

// Input array
input.items = [
  { id: 1, value: 100 },
  { id: 2, value: 200 },
  { id: 3, value: 300 }
]

// Each iteration receives
currentItem = { id: 1, value: 100 }
currentIndex = 0

Fixed Count

Repeat a specific number of times:

// Configuration
iterations: 5

// Each iteration receives
currentIndex: 0, 1, 2, 3, 4

While Condition

Continue until condition is false:

// Configuration
condition: "input.retries < 5 && !input.success"

// Continues while condition is true

Loop Settings

Array Source

Path to the array in your input:

// Direct array
"items"  // → input.items

// Nested array
"data.records"  // → input.data.records

// Dynamic path
"{{category}}.products"  // → input[category].products

Max Iterations

Safety limit to prevent infinite loops:

  • Default: 1000
  • Adjustable based on needs
  • Prevents runaway execution

Batch Size

Process items in groups:

// Process 10 items at a time
batchSize: 10

// Useful for API rate limits
// Reduces memory usage for large arrays

Processing Items

Current Item Access

Inside the loop, nodes receive:

{
  currentItem: /* Current array element */,
  currentIndex: /* Index (0-based) */,
  totalItems: /* Array length */,
  isFirst: /* true for first item */,
  isLast: /* true for last item */,
  previousResults: /* Results from previous iterations */
}

Using in Downstream Nodes

In Code nodes:

// Process current item
const item = input.currentItem;
const processed = {
  ...item,
  processedAt: Date.now(),
  index: input.currentIndex
};
return processed;

In Agent nodes:

Analyze this product review:
{{currentItem.review}}

This is item {{currentIndex}} of {{totalItems}}.

Accumulating Results

Result Aggregation

Loop nodes automatically collect results:

// After loop completes, output contains:
{
  results: [
    /* Result from iteration 0 */,
    /* Result from iteration 1 */,
    /* Result from iteration 2 */
  ],
  summary: {
    totalProcessed: 3,
    successful: 3,
    failed: 0
  }
}

Aggregation Strategies

Collect All (Default)

Returns array of all results:

[result1, result2, result3, ...]

Merge Objects

Combines results into single object:

{
  ...result1,
  ...result2,
  ...result3
}

Sum Values

Accumulates numeric results:

result1 + result2 + result3

Custom Aggregation

Use Code node after loop for custom logic:

// Calculate statistics
const results = input.results;
return {
  total: results.reduce((sum, r) => sum + r.value, 0),
  average: results.reduce((sum, r) => sum + r.value, 0) / results.length,
  max: Math.max(...results.map(r => r.value)),
  min: Math.min(...results.map(r => r.value))
};

Common Patterns

Data Transformation

// Loop through users
// Inside loop: Code node
const user = input.currentItem;
return {
  id: user.userId,
  fullName: `${user.firstName} ${user.lastName}`,
  email: user.emailAddress.toLowerCase(),
  status: user.isActive ? 'active' : 'inactive'
};

API Batch Processing

// Loop with batch size: 10
// Inside loop: Plugin node for API
// Processes 10 items per API call
{
  batch: input.currentBatch,
  batchIndex: input.batchIndex
}

Filtering and Processing

// Inside loop: Condition node
input.currentItem.status === 'pending'

// True branch: Process item
// False branch: Skip to next

Retry Logic

// Fixed loop: 5 iterations
// Inside: Try operation
// Check success and break early if done
if (input.operationResult.success) {
  return {
    success: true,
    attempts: input.currentIndex + 1
  };
}

Advanced Techniques

Nested Loops

Process multi-dimensional data:

// Outer loop: Categories
// Inner loop: Products in category
input.categories.forEach(category => {
  category.products.forEach(product => {
    // Process each product
  });
});

Parallel Processing

Enable concurrent iteration:

// Configuration
parallelism: 5  // Process 5 items simultaneously

// Useful for:
// - API calls
// - Independent transformations
// - I/O operations

Early Exit

Stop loop based on condition:

// In Code node inside loop
if (input.currentItem.stopProcessing) {
  return {
    shouldContinue: false,
    message: "Stop condition met"
  };
}

Dynamic Arrays

Generate array to loop over:

// In Code node before loop
// Generate date range
const dates = [];
const start = new Date('2024-01-01');
const end = new Date('2024-01-31');
for (let d = start; d <= end; d.setDate(d.getDate() + 1)) {
  dates.push(new Date(d));
}
return { datesToProcess: dates };

Use Cases

Bulk Email Processing

Loop: Each recipient
├── Agent: Personalize message
├── Plugin: Send email
└── Code: Log result

Data Validation

Loop: Each record
├── Code: Validate format
├── Condition: Check validity
│   ├── True: Store valid
│   └── False: Log error
└── Accumulate results

Report Generation

Loop: Each department
├── Plugin: Fetch metrics
├── Agent: Generate summary
├── Code: Format section
└── Join: Combine report

Inventory Updates

Loop: Each product
├── Plugin: Check stock
├── Condition: Low stock?
│   └── True: Create alert
└── Update database

Performance Optimization

Batch Processing

// Instead of 1000 individual API calls
batchSize: 50  // 20 batched calls

// Reduces overhead
// Respects rate limits
// Improves throughput

Parallel Execution

// Process independent items concurrently
parallelism: 10

// 10x faster for I/O operations
// Maintain reasonable limits
// Monitor resource usage

Memory Management

// For large datasets
// Process in chunks
// Clear intermediate results
// Use streaming when possible

Error Handling

Per-Item Error Handling

// Inside loop: Code node
try {
  // Process item
  return {
    success: true,
    data: processedData
  };
} catch (error) {
  return {
    success: false,
    error: error.message,
    item: input.currentItem
  };
}

Continue on Error

// Configuration
continueOnError: true

// Failed items don't stop loop
// Errors collected in results
// Process all possible items

Retry Failed Items

// After loop: Code node
const failed = input.results.filter(r => !r.success);
if (failed.length > 0) {
  return {
    retry: true,
    failedItems: failed.map(f => f.item)
  };
}

Best Practices

1. Use AI for Complex Logic

Let AI help with intricate iterations:

✨ "Process orders by priority, batch by region"
✨ "Retry with exponential backoff"
✨ "Group and aggregate by multiple fields"

2. Set Reasonable Limits

// Always set max iterations
maxIterations: 10000  // Prevent infinite loops

// Use batch sizes for large arrays
batchSize: 100  // Process in chunks

3. Handle Empty Arrays

// Check before loop
if (!input.items || input.items.length === 0) {
  return { message: "No items to process" };
}

4. Monitor Performance

// Log progress for long loops
if (input.currentIndex % 100 === 0) {
  console.log(`Processed ${input.currentIndex} of ${input.totalItems}`);
}

Troubleshooting

"Maximum iterations exceeded"

  • Reduce array size
  • Increase max iterations limit
  • Check for infinite loop conditions

"Memory limit reached"

  • Use smaller batch sizes
  • Process in multiple workflows
  • Clear intermediate results

"Slow performance"

  • Enable parallel processing
  • Optimize operations inside loop
  • Consider batch processing

"Results not accumulating"

  • Check aggregation strategy
  • Ensure nodes return values
  • Verify result structure

Examples

Customer Order Processing

// Loop through orders
input.orders.forEach(order => {
  // Calculate totals
  const subtotal = order.items.reduce((sum, item) => 
    sum + (item.price * item.quantity), 0
  );
  
  // Apply discounts
  const discount = order.coupon ? subtotal * 0.1 : 0;
  
  // Add shipping
  const total = subtotal - discount + order.shipping;
  
  return {
    orderId: order.id,
    subtotal,
    discount,
    total
  };
});

Batch API Updates

// Process users in batches of 25
// Inside loop: Plugin node
updateUsers({
  users: input.currentBatch,
  operation: 'activate',
  timestamp: Date.now()
});

Data Enrichment

// Loop through records
// Inside: Multiple nodes
// 1. Plugin: Fetch additional data
// 2. Agent: Analyze and classify
// 3. Code: Merge and transform
// Result: Enriched dataset

Related Topics