0

When I used axios.post, I met this problem

var len =5;
var a ={};
function abc(temp){
  console.log(temp);
  axios.post("/",temp);
}
while(len--){
  a.name = len;
  abc(a);
}

when I run this code in console, it will send 5 time request with the same payload.

The cause is var || let ?

but when I used $.ajax, it works normally.

I wanna an answer, Thanks a lot.

Nic.li
  • 1
  • 1
  • Axios is an async library which you are running through synchronous code. This is why it does not work. – cbronson Aug 11 '17 at 17:18
  • Possible duplicate of [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Bert Aug 11 '17 at 17:18

1 Answers1

0

The issue you have is scope of the variable a in the abc function call.

while(len--) {
   let length = len;
   abc( { name: length } );
}

This creates a new variable length for every iteration and scope is restricted to that iteration.

The answers to this question JavaScript closure inside loops – simple practical example explain in detail about why this happens and about scope and closure in JavaScript. The above question is an exact duplicate of this question.

  • I have tried let a new object ,it works ,but i don't not the reason why in my case, i just change axios to $.ajax, it works normally , i don't need let a new object for it – Nic.li Aug 13 '17 at 13:55