JavaScript异步任务优化

指尖流年 +0/-0 0 0 正常 2025-12-24T07:01:19 JavaScript · Promise

在现代JavaScript开发中,异步任务优化是提升应用性能的关键环节。本文将通过实际代码示例展示如何有效优化Promise和async/await的异步任务处理。

并发控制优化

传统的Promise.all()虽然简单高效,但在大量请求场景下可能导致资源耗尽。我们可以通过限制并发数量来优化:

function limitConcurrency(tasks, limit = 3) {
  return new Promise((resolve, reject) => {
    let index = 0;
    let running = 0;
    const results = [];
    
    function run() {
      if (index >= tasks.length && running === 0) {
        resolve(results);
        return;
      }
      
      while (running < limit && index < tasks.length) {
        running++;
        const task = tasks[index];
        index++;
        
        task().then(result => {
          results.push(result);
          running--;
          run();
        }).catch(error => {
          reject(error);
        });
      }
    }
    
    run();
  });
}

// 使用示例
const tasks = [
  () => fetch('/api/data1').then(res => res.json()),
  () => fetch('/api/data2').then(res => res.json()),
  () => fetch('/api/data3').then(res => res.json()),
  () => fetch('/api/data4').then(res => res.json())
];

limitConcurrency(tasks, 2).then(results => {
  console.log('并发优化结果:', results);
});

缓存机制优化

对于重复的异步请求,添加缓存可以显著提升性能:

const cache = new Map();

async function cachedFetch(url, options = {}) {
  const cacheKey = `${url}_${JSON.stringify(options)}`;
  
  if (cache.has(cacheKey)) {
    console.log('从缓存获取数据');
    return cache.get(cacheKey);
  }
  
  const response = await fetch(url, options);
  const data = await response.json();
  
  // 设置5分钟缓存
  cache.set(cacheKey, data);
  setTimeout(() => cache.delete(cacheKey), 300000);
  
  return data;
}

// 使用示例
async function loadUserData() {
  const user = await cachedFetch('/api/user/123');
  const posts = await cachedFetch('/api/user/123/posts');
  return { user, posts };
}

错误处理与重试机制

优化的异步任务应该具备完善的错误处理和自动重试能力:

async function retryAsync(fn, retries = 3, delay = 1000) {
  for (let i = 0; i <= retries; i++) {
    try {
      return await fn();
    } catch (error) {
      if (i === retries) throw error;
      console.log(`请求失败,${delay}ms后重试...`);
      await new Promise(resolve => setTimeout(resolve, delay));
      delay *= 2; // 指数退避
    }
  }
}

// 使用示例
async function fetchWithRetry() {
  return retryAsync(() => fetch('/api/some-endpoint').then(res => res.json()), 3, 500);
}

通过以上优化策略,可以显著提升异步任务的执行效率和用户体验。

推广
广告位招租

讨论

0/2000