Workflows
Blocks
Logic
For Each

ForEach Block

What it does: Perform actions on every item in a list or array automatically.

📋

In simple terms: Like going through a to-do list and doing something with each item - "for each customer, send an email" or "for each file, process and upload".

When to Use This

Use the ForEach block when you need to:

  • ✅ Process multiple items from a list
  • ✅ Send emails to multiple recipients
  • ✅ Process uploaded files one by one
  • ✅ Update multiple database records
  • ✅ Create tasks for each item
  • ✅ Transform array data

Example: For each row in a spreadsheet, create a personalized email and send it to the customer.

How It Works

  1. Input: Provide an array of items
  2. Iterate: Go through each item one by one
  3. Process: Execute actions for current item
  4. Repeat: Move to next item
  5. Complete: Finish when all items processed

Configuration

Input Array

Array Source: Where your list comes from

{{spreadsheet.rows}}
{{api.response.users}}
{{form.selectedItems}}
["item1", "item2", "item3"]

Example Arrays:

// List of users
[
  {"name": "John", "email": "john@example.com"},
  {"name": "Jane", "email": "jane@example.com"}
]
 
// List of IDs
[101, 102, 103, 104]
 
// List of strings
["file1.pdf", "file2.pdf", "file3.pdf"]

Current Item Access

Inside the ForEach loop, access the current item:

Simple Values:

{{item}} - Current item
{{item.index}} - Index (0, 1, 2...)
{{item.value}} - The actual value

Object Properties:

{{item.name}}
{{item.email}}
{{item.id}}
{{item.any_property}}

Array Items:

{{item[0]}} - First element
{{item[1]}} - Second element

Loop Control

Iteration Info:

{{forEach.index}} - Current position (0-based)
{{forEach.iteration}} - Current iteration (1-based)
{{forEach.total}} - Total items in array
{{forEach.isFirst}} - true if first item
{{forEach.isLast}} - true if last item

Control Flow:

{{forEach.continue}} - Skip to next item
{{forEach.break}} - Exit loop early

Processing Options

Sequential Processing

Process items one after another (default).

Use when:

  • Order matters
  • Each item depends on previous
  • Rate limiting required
  • Consistent timing needed

Example:

For each customer in list:
  1. Send email (wait for confirmation)
  2. Update database
  3. Log result
  Then move to next customer

Parallel Processing

Process multiple items at once.

Use when:

  • Items are independent
  • Speed is critical
  • No dependencies between items
  • API allows concurrent requests
⚠️

Be careful with parallel processing - it can overwhelm APIs and hit rate limits quickly!

Example:

For each image in list (parallel):
  - Upload to cloud storage
  All 10 images upload simultaneously

Concurrency Limit:

Max Parallel: 5
(Process 5 items at a time)

Common Use Cases

Example 1: Bulk Email Sending

Array: List of subscribers

[
  {"name": "Alice", "email": "alice@example.com", "plan": "premium"},
  {"name": "Bob", "email": "bob@example.com", "plan": "free"}
]

ForEach Actions:

For each subscriber:
  1. Set Variable: personalizedMessage
     "Hi {{item.name}}, enjoy your {{item.plan}} plan!"
     
  2. Send Email:
     To: {{item.email}}
     Subject: "Special Offer"
     Body: {{personalizedMessage}}
     
  3. Wait: 2 seconds (rate limiting)

Example 2: File Processing

Array: Uploaded files

[
  {"filename": "doc1.pdf", "url": "https://..."},
  {"filename": "doc2.pdf", "url": "https://..."}
]

ForEach Actions:

For each file:
  1. HTTP Request: Download file
     GET {{item.url}}
     
  2. File Loader: Extract text
     URL: {{item.url}}
     
  3. Database: Store content
     Collection: documents
     Data: {
       name: {{item.filename}},
       content: {{fileLoader.text}},
       processed: {{currentTime}}
     }

Example 3: Database Updates

Array: Records to update

[
  {"id": "101", "status": "pending"},
  {"id": "102", "status": "pending"}
]

ForEach Actions:

For each record:
  1. HTTP Request: Process record
     POST /api/process/{{item.id}}
     
  2. Condition: Check result
     If {{response.success}} == true:
       
       3. Database: Update status
          Update document {{item.id}}
          Set: {status: "completed"}

Example 4: Social Media Posts

Array: Post content

[
  {"platform": "Twitter", "message": "Hello Twitter!"},
  {"platform": "LinkedIn", "message": "Hello LinkedIn!"}
]

ForEach Actions:

For each post:
  1. Condition: Route by platform
     
     If {{item.platform}} == "Twitter":
       HTTP Request: Post to Twitter
       
     If {{item.platform}} == "LinkedIn":
       HTTP Request: Post to LinkedIn
       
  2. Wait: 5 minutes between posts

Example 5: Multi-Step Processing

Array: Orders to fulfill

[
  {"orderId": "ORD-001", "items": ["item1", "item2"], "customer": {"email": "user@example.com"}},
  {"orderId": "ORD-002", "items": ["item3", "item4"], "customer": {"email": "user2@example.com"}}
]

ForEach Actions:

For each order:
  1. For each item in {{item.items}}:
     - Check inventory
     - Reserve stock
     
  2. Generate invoice
     Create PDF with order details
     
  3. Send Email:
     To: {{item.customer.email}}
     Attach: Generated invoice
     
  4. Update Order Status:
     Database update: status = "processed"

Advanced Patterns

Nested ForEach

Process arrays within arrays.

For each department:
  For each employee in {{item.employees}}:
    Send welcome email to {{employee.email}}
⚠️

Nested loops can grow exponentially. 10 departments × 50 employees = 500 iterations!

Filtering Items

Skip items based on condition.

For each user:
  Condition: If {{item.age}} >= 18:
    Continue with actions
  Else:
    Skip (continue to next)

Accumulating Results

Collect outputs from each iteration.

Set Variable: results = []

For each item:
  1. Process item
  2. Append {{processedData}} to {{results}}

After loop: {{results}} contains all outputs

Error Handling

Handle failures gracefully.

For each file:
  Try:
    1. Process file
    2. Upload result
  Catch error:
    Log error
    Add to {{failedFiles}} list
  Continue to next item

Conditional Break

Exit loop early when condition met.

For each candidate:
  If {{item.score}} > 95:
    Select candidate
    Break loop (found perfect match)
  Else:
    Continue searching

Response Mapping

Capture ForEach results:

Total Processed → {{forEach.totalProcessed}}
Success Count → {{forEach.successCount}}
Failed Count → {{forEach.failedCount}}
Results Array → {{forEach.results}}
Last Item → {{forEach.lastItem}}
Duration → {{forEach.duration}}

Best Practices

Array Handling

  • Validate array exists before ForEach
  • Check array is not empty
  • Limit array size for large datasets (batch processing)
  • Handle null/undefined items
  • Use clear item naming

Performance

  • Add delays for API rate limiting
  • Batch operations when possible
  • Use parallel processing for independent items
  • Limit concurrency to avoid overwhelming services
  • Monitor execution time

Error Handling

  • Wrap actions in error handling
  • Log failures for debugging
  • Don't let one failure stop all
  • Track failed items separately
  • Implement retry logic for transient failures

Data Management

  • Clear large variables after use
  • Avoid accumulating too much data
  • Use pagination for huge datasets
  • Store results externally if needed
  • Clean up temporary files

Troubleshooting

ForEach Not Running

Check:

  • Array variable is defined
  • Array is not empty
  • Array is valid JSON format
  • Variable path is correct

Debug:

Add before ForEach:
  Log: "Array: {{myArray}}"
  Log: "Length: {{myArray.length}}"

Wrong Item Data

Issues:

  • Using {{item}} instead of {{item.propertyName}}
  • Index confusion (0-based vs 1-based)
  • Nested object access errors

Fix:

Log current item:
  Log: "Processing: {{item}}"
  
Access correctly:
  {{item.email}} not {{item[email]}}

Performance Degradation

Causes:

  • Too many items processed sequentially
  • No delays causing rate limits
  • Memory accumulation
  • Heavy operations per item

Solutions:

  • Add delays: Wait 1 second between items
  • Enable parallel processing
  • Process in smaller batches
  • Optimize actions per item

Incomplete Processing

Reasons:

  • Workflow timeout
  • Error stopping loop
  • Break condition triggered early
  • Resource limits

Solutions:

  • Reduce batch size
  • Add error handling to continue
  • Check break conditions
  • Monitor workflow logs

Limitations

  • Max Items: Recommended limit 1000 items per ForEach
  • Nested Depth: Avoid more than 2-3 levels of nesting
  • Execution Time: Subject to workflow timeout
  • Memory: Large arrays consume memory
  • Parallel Limit: Max concurrent operations varies
💡

Tip: For very large datasets (10,000+ items), split into batches and run separate workflows for each batch!

Example Workflow

Related Blocks

  • Condition: Filter items during iteration
  • Set Variable: Prepare array or store results
  • Loop: Use for retry or polling instead
  • HTTP Request: Common action per item
  • Database: Fetch arrays or store results
  • Wait: Add delays between iterations

Need Help?

  • Verify array structure before ForEach
  • Start with small test arrays
  • Add logging inside loop
  • Monitor execution for performance
  • Use conditions to skip items
  • Consider parallel processing for speed

Pro Tip: Combine ForEach with Condition blocks to create powerful data filtering and transformation pipelines!

Indite Documentation v1.4.0
PrivacyTermsSupport