2

Currently I am trying to run a for loop that says for each JSON object in a array create an axios post call and add it to an Array. Then I am using Axios.all to call them all at once. The issue I'm having is the JSON post object is the same for each of the post calls.

let axiosArray = []
let postData = {}
for (int x = 0; x < numOfItems; x++) {

postData['size'] = shoe.size
postData['color'] = shoe.color
let newPromise = axios({
  method: 'post',
  url: postShoe,
  data: postData
})
  .then(responsed => {
    console.log('success')
  })
  .catch(error => {

    console.log('error')
  })
  axiosArray.push(newPromise)
}
  axios
.all(axiosArray)
.then(() => {
  console.log('submitted all axios calls')
})
.catch(error => {})

It runs two post calls like I want but its using the last value supplied to postData for each of the calls. I am wondering if there is a way to save all the data in the promise as it is when I create it and then on submit it will not only use the last value supplied to the postData.

Totals
  • 311
  • 2
  • 5
  • 14

1 Answers1

7

axios.all expects to receive a unhandled promise without the then. To iterate over the responses axios.spread accepts the responses as its arguments. The code below should work(Could certainly be more concise).

let axiosArray = []
for (int x = 0; x < numOfItems; x++) {
  let postData = {}
  postData['size'] = shoe.size
  postData['color'] = shoe.color
  let newPromise = axios({
      method: 'post',
      url: postShoe,
      data: postData
    })
  axiosArray.push(newPromise)
}

axios
  .all(axiosArray)
  .then(axios.spread((...responses) => {
    responses.forEach(res => console.log('Success'))
    console.log('submitted all axios calls');
  }))
  .catch(error => {})

You could also refer this post which is similar to your question.

karuhanga
  • 3,010
  • 1
  • 27
  • 30
  • the issue im having isnt the responses. Its that each post call is using the same postData json structure. If I want to add 300 shoes it'll only add the last one entered 300 times instead of what the postData was at the time the promise was created. – Totals Mar 08 '18 at 15:58
  • That is because the `postData` is declared outside the loop, javascript accessed objects by reference. Declaring the `postData` object within the loop will solve the issue. I have edited the answer to reflect the same. – Gokul Chandrasekaran Mar 08 '18 at 16:51
  • i keep getting the message axios.all is not a function – rrrm93 Jul 31 '19 at 15:19
  • there are 18 items in an array but it's only inserting one item of them. so, only one promise is working. what should i do in this case? – yusufcode Apr 15 '22 at 00:03