js 实现 ajax 并发请求

  1. Promise.all 并发请求(全部完成后处理)
javascript 复制代码
// 使用 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(不管成败都处理)
javascript 复制代码
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 个)
javascript 复制代码
// 并发控制工具
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));

特点:

  • 适合需要防止高并发压垮服务器的场景
  • 一批批并发执行
相关推荐
深蓝海拓2 分钟前
使用@property将类方法包装为属性
开发语言·python
雨雨雨雨雨别下啦12 分钟前
Vue3——RabbitShopping
前端·javascript·vue.js
xiaoye-duck15 分钟前
【C++:unordered_set和unordered_map】 深度解析:使用、差异、性能与场景选择
开发语言·c++·stl
BumBle17 分钟前
从声明式到命令式:Vue3 弹窗组件的工厂模式重构
前端
恋猫de小郭23 分钟前
你的蓝牙设备可能正在泄漏你的隐私? Bluehood 如何追踪附近设备并做隐私分析
android·前端·ios
zjjsctcdl30 分钟前
java与mysql连接 使用mysql-connector-java连接msql
java·开发语言·mysql
格林威34 分钟前
Baumer相机锂电池极片裁切毛刺检测:防止内部短路的 5 个核心方法,附 OpenCV+Halcon 实战代码!
开发语言·人工智能·数码相机·opencv·计算机视觉·c#·视觉检测
顶点多余44 分钟前
线程互斥+线程同步+生产消费模型
java·linux·开发语言·c++
Albert Edison1 小时前
【ProtoBuf 语法详解】更新消息|保留字段|未知字段
开发语言·c++·protobuf
feifeigo1231 小时前
近场声全息(NAH)数据与MATLAB实现
开发语言·matlab