isul
isul

Reputation: 5

How call multiple function in loop

I have tried to call multiple function like below. But the result is undefined...

let result='';
    for (let i = 0; i<req.body.length; i++){
         return result += function() {
            return axiosInstanceCost.post('/starter/cost', qs.stringify({
                'origin': req.body.origin[i],
                'weight': req.body.weight[i],
                'destination': req.body.destination[i],
                'courier': req.body.courier[i]
             }))    
        };
    }    

    axios.all(result)
        .then(axios.spread(function(response){
            console.log(response);            

        }))
        .catch(function(error){
            console.log(error)
        })

Please tell me the right code. Thanks a alot before.

Upvotes: 0

Views: 62

Answers (1)

Ramesh Reddy
Ramesh Reddy

Reputation: 10662

I think you're trying to create an array of promises and do something when all of them resolve...something like:

const result = [];
for (let i = 0; i < req.body.length; i++) {
  result.push(
    axiosInstanceCost.post('/starter/cost', qs.stringify({
      'origin': req.body.origin[i],
      'weight': req.body.weight[i],
      'destination': req.body.destination[i],
      'courier': req.body.courier[i]
    })));
}

axios.all(result)
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error)
  })

Upvotes: 1

Related Questions