agentsqripts
Version:
Comprehensive static code analysis toolkit for identifying technical debt, security vulnerabilities, performance issues, and code quality problems
62 lines (53 loc) • 2.41 kB
JavaScript
/**
* @file Detect async operations in loops
* @description Single responsibility: Find async operations in loops that could be parallelized
* NOTE: While some detections may be false positives, they are valuable for
* LLM code inspection to identify potential parallelization opportunities.
* Sequential await operations in loops can often be optimized with Promise.all()
* for significant performance gains (70-90% latency reduction).
*/
const { iterateLines, isLoopPattern, isSmallFixedLoop, hasEarlyExit } = require('../../../utils/patternDetector');
function detectAsyncInLoops(lines, filePath) {
const issues = [];
iterateLines(lines, (line, lineNumber, trimmed, i) => {
// Look for loops - but skip small/fixed iterations
if (isLoopPattern(trimmed)) {
// Skip if it's a small fixed loop
if (isSmallFixedLoop(trimmed)) {
return;
}
// Check for await in loop body
for (let j = i + 1; j < Math.min(i + 10, lines.length); j++) {
const innerLine = lines[j].trim();
if (/await\s+/.test(innerLine)) {
// Skip if it's a single operation or has early exit
const contextEnd = Math.min(lines.length, j + 5);
const hasEarlyExit = lines.slice(j, contextEnd).some(l => /break|return|continue/.test(l));
if (hasEarlyExit) continue;
const isForEach = /\.forEach\s*\(/.test(trimmed);
const isMap = /\.map\s*\(/.test(trimmed);
// Only flag forEach with async as HIGH severity (it's actually problematic)
if (isForEach) {
issues.push({
type: 'async_in_loop',
severity: 'HIGH',
category: 'Async',
location: `${filePath}:${j + 1}`,
line: j + 1,
code: innerLine,
description: `Async operation in forEach - forEach doesn't handle promises correctly`,
summary: 'Async operation in loop creates sequential execution',
recommendation: 'Use for...of with await or Promise.all for proper async handling',
effort: 2,
impact: '70-90% latency reduction for parallel operations',
estimatedSavings: '70-90% latency reduction'
});
}
break;
}
}
}
});
return issues;
}
module.exports = detectAsyncInLoops;