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

为何仅获取最后一个Promise?Axios多Promise处理异常排查

解决Promise请求参数被覆盖的问题

Hey there! I totally get why this is happening—let's dive into the root cause first, then fix it up.

The Problem: Shared Object Reference

You're modifying the same params object in every iteration of your map loop. Since objects in JavaScript are passed by reference, every axios.post call ends up using that single shared params object. By the time all the Promises start executing, params.meter has already been updated to the last value in your meters array (powertTrack2007), which is why every response you get uses that final meter value.

Your original code wrapped the axios call in an extra function, but that doesn't fix the reference issue—it just adds unnecessary complexity.

The Fix: Create a Unique Params Object for Each Request

The solution is simple: make a fresh copy of params for every iteration, so each request gets its own independent set of parameters. Here's how to adjust your code:

// 重新构建Promise数组,每次循环创建新的params对象
const powerPlants = meters.map(meter => {
  // 使用展开运算符复制原有params,并覆盖meter字段
  const requestParams = { ...params, meter };
  // 直接返回axios.post的Promise,不需要额外包装函数
  return axios.post(
    'https://power.ivyiot.com/Thingworx/Things/GamaNetworkServices/Services/GetHistoricDataByMinute',
    requestParams,
    options
  );
});

axios.all(powerPlants).then(axios.spread((a,b,c,d,e,f,g)=>{
  console.log(a); // 现在a会对应powertTrack2001的正确响应啦!
}))

If you're working in an environment that doesn't support the spread operator (...), you can use Object.assign instead:

const requestParams = Object.assign({}, params, { meter });

Why This Works

By creating a new requestParams object in each loop iteration, we ensure each axios.post call gets its own unique parameter set. No more overwriting the same object—each Promise will send the correct meter value corresponding to its position in the meters array.

Your use of axios.all() and axios.spread() is totally correct once the parameter issue is fixed—they'll handle waiting for all Promises and spreading the responses in order perfectly.

内容的提问来源于stack exchange,提问作者Harun Keleşoğlu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:14:45