js 实现 ajax 并发请求

发布于:2025-08-11 ⋅ 阅读:(16) ⋅ 点赞:(0)
  1. Promise.all 并发请求(全部完成后处理)
// 使用 fetch 作为示例
function getData(url) {
  return fetch(url).then(res => res.json());
}

Promise.all([
  getData('/api/user'),
  getData('/api/order'),
  getData('/api/cart')
])
.then(([user, order, cart]) => {
  console.log('用户数据:', user);
  console.log('订单数据:', order);
  console.log('购物车数据:', cart);
})
.catch(err => {
  console.error('其中一个请求失败:', err);
});

特点:

  • 所有请求是同时发出的
  • 只有全部成功才进入 .then,有一个失败就进入 .catch
  1. Promise.allSettled(不管成败都处理)
Promise.allSettled([
  fetch('/api/user').then(res => res.json()),
  fetch('/api/order').then(res => res.json()),
  fetch('/api/cart').then(res => res.json())
])
.then(results => {
  results.forEach((result, index) => {
    if (result.status === 'fulfilled') {
      console.log(`${index+1}个成功:`, result.value);
    } else {
      console.error(`${index+1}个失败:`, result.reason);
    }
  });
});

特点:

  • 不会因为某个失败而中断
  • 每个请求的状态都会返回
  1. 限制并发数(比如同时只能跑 2 个)
// 并发控制工具
async function limitConcurrency(urls, limit) {
  const results = [];
  const queue = [...urls];

  async function worker() {
    while (queue.length) {
      const url = queue.shift();
      try {
        const res = await fetch(url).then(r => r.json());
        results.push(res);
      } catch (err) {
        results.push(err);
      }
    }
  }

  const workers = Array.from({ length: limit }, worker);
  await Promise.all(workers);
  return results;
}

// 用法
limitConcurrency(['/api/1', '/api/2', '/api/3', '/api/4'], 2)
  .then(res => console.log('结果:', res));

特点:

  • 适合需要防止高并发压垮服务器的场景
  • 一批批并发执行

网站公告

今日签到

点亮在社区的每一天
去签到