# Await in Loop
# Detects sequential await calls inside loops (performance anti-pattern)
id: await-in-loop
name: Await in Loop
severity: warning
category: performance
defect_class: injection
inline_tier: blocking
language: typescript

message: "Await in loop — sequential execution is slow, use Promise.all()"

description: |
  Using await inside a loop forces sequential execution, making it O(n) time.
  With Promise.all(), operations run in parallel, making it O(1) time.
  
  ✅ FIX: Use Promise.all() for parallel execution
  
  ⚠️ EXCEPTION: If order matters or you need to throttle requests, sequential 
  may be intentional. In that case, add a comment explaining why.

query: |
  (for_in_statement
    body: (statement_block
      (expression_statement
        (await_expression) @AWAIT)))
  (for_statement
    body: (statement_block
      (expression_statement
        (await_expression) @AWAIT)))
  (while_statement
    body: (statement_block
      (expression_statement
        (await_expression) @AWAIT)))

metavars:
  - AWAIT

tags:
  - performance
  - async
  - optimization

examples:
  bad: |
    // Slow: sequential execution
    for (const id of ids) {
      await fetchUser(id);  // Wait, wait, wait...
    }
  
  good: |
    // Fast: parallel execution
    await Promise.all(
      ids.map(id => fetchUser(id))  // All at once!
    )

has_fix: true
fix_action: convert_to_promise_all
