为什么我得到最后的承诺? [英] Why I getting the last promise?

查看:84
本文介绍了为什么我得到最后的承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尽力履行所有诺言.但是我只得到最后的诺言吗?我看了npm axios模块.代码在其中运行:

I am trying handle all promise.But i getting only the last promise? I looked npm axios module.Code is run in that:

 axios.all([f1(), f2()]).then(axios.spread(function(res1, res2) { //handle }));

我为保持承诺函数创建了一个名为powerPlants的新数组:

I create new array named powerPlants for hold promise functions:

  const powerPlants = meters.map( meter => {
     const obj = {};
     params.meter = meter; //  changing parameter for post request
     obj[meter] = function(){
        return axios.post('https://power.ivyiot.com/Thingworx/Things/GamaNetworkServices/Services/GetHistoricDataByMinute',params,options);
     };    
    return obj[meter]();           });

我想按以下方式分别处理所有诺言.但不起作用.

and i want to handle all promise seperately as below.But is not working.

 axios.all(powerPlants).then(axios.spread((a,b,c,d,e,f,g)=>{
        console.log(a); //meter parameter of a should be powertTrack2001 but it powerTrack2007 
}))

推荐答案

只有一个params对象,您要更改其.meter属性-它以最后分配的值结尾.鉴于此对象是您的承诺结果的一部分,所以到处都是相同的.制作params的副本可避免这种情况:

You have only a single params object whose .meter property you are changing - it ends up with the last assigned value. Given that this object is part of your promise result, it's the same everywhere. Make a copy of your params to avoid this:

axios.all(meters.map(meter => {
    const paramObj = Object.assign({}, params, {meter});
    return axios.post('https://power.ivyiot.com/Thingworx/Things/GamaNetworkServices/Services/GetHistoricDataByMinute', paramObj, options);
})).then(…)

这篇关于为什么我得到最后的承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆