async function readFileContent(filePath) {
// 模拟异步解析文件内容
return new Promise((resolve) => {
setTimeout(() => {
resolve(`Content of ${filePath}`);
}, 100);
});
}
async function processFiles(filePaths) {
const maxConcurrent = 5;
const tasks = [];
for (let i = 0; i < filePaths.length; i++) {
tasks.push(readFileContent(filePaths[i]));
if (tasks.length === maxConcurrent || i === filePaths.length - 1) {
const results = await Promise.all(tasks);
results.forEach((result) => {
console.log(result);
});
tasks.length = 0;
}
}
}
// 假设从数据库读取的文件路径
const filePaths = Array.from({ length: 20 }, (_, i) => `file${i + 1}.txt`);
processFiles(filePaths);
性能优化说明
- 资源控制:通过设置
maxConcurrent
为 5,确保在任何时刻最多只有 5 个异步操作在执行,避免系统资源(如内存、网络连接等)被大量并发请求耗尽。
- 负载均衡:分批处理文件路径,当一批任务(5 个)完成后,再处理下一批,使系统的负载更加均衡,不会因为瞬间的高并发导致系统崩溃或性能急剧下降。
- 内存管理:减少同时处于活跃状态的异步任务数量,有助于更好地管理内存,防止因大量未完成的异步任务占用过多内存而导致内存溢出等问题。