Why I getting the last promise?

2019-06-14 15:12发布

问题:

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 }));

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 
}))

回答1:

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(…)