You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何利用Fetch API批量发起仅路径参数不同的请求?

批量请求商品价格的实现方案

单次Fetch API调用无法直接同时请求多个不同的URL——因为Fetch本身是为单次请求单个资源设计的。不过你完全可以通过循环结合Promise的方式实现批量请求,下面是两种常用的实现方式:

并行请求(效率优先)

用Promise.all配合数组map一次性发起所有请求,所有请求同时进行,完成后统一处理结果,适合API没有频率限制的场景:

// 定义商品标识列表
const items = ['item1', 'item2', 'item3', 'item4', 'item5'];

// 生成所有请求的Promise实例
const fetchTasks = items.map(item => {
  const apiUrl = `https://www.apirequest/${item}/ps2`;
  return fetch(apiUrl)
    .then(res => {
      if (!res.ok) throw new Error(`请求商品${item}失败,状态码: ${res.status}`);
      return res.json(); // 假设API返回JSON格式数据,包含price字段
    })
    .then(data => ({ item, price: data.price })) // 关联商品标识和价格
    .catch(err => ({ item, error: err.message })); // 捕获单个请求的错误,不影响其他请求
});

// 等待所有请求完成
Promise.all(fetchTasks)
  .then(results => {
    console.log('所有查询结果:', results);
    // 筛选成功获取到价格的结果
    const validPrices = results.filter(r => !r.error);
    console.log('有效商品价格:', validPrices);
  });

串行请求(适合有频率限制的场景)

如果API有请求频率限制,不想一次性发送太多请求,可以用async/await配合循环逐个发起请求,还可以添加间隔时间:

async function getPricesSequentially() {
  const items = ['item1', 'item2', 'item3', 'item4', 'item5'];
  const results = [];

  for (const item of items) {
    try {
      const apiUrl = `https://www.apirequest/${item}/ps2`;
      const res = await fetch(apiUrl);
      if (!res.ok) throw new Error(`商品${item}请求失败: ${res.status}`);
      const data = await res.json();
      results.push({ item, price: data.price });
    } catch (err) {
      results.push({ item, error: err.message });
      // 这里可以选择中断循环,或者继续执行,示例中选择继续
    }
    // 可选:每个请求之间间隔1秒,避免触发频率限制
    await new Promise(resolve => setTimeout(resolve, 1000));
  }

  console.log('串行查询结果:', results);
}

// 执行函数
getPricesSequentially();

补充说明:如果你的后端提供了批量查询接口(比如可以一次性传入多个item标识,返回所有对应价格),那确实可以用单次Fetch请求这个接口,但根据你给出的API格式,目前没有这样的接口,所以上述循环批量请求的方式是最合适的。

内容的提问来源于stack exchange,提问作者jithin surendran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 15:55:16