0

I am using the node package p-queue (GitHub repo) in order to ensure that the axios.get requests from my app are sequential and at a max rate of 1 per second.

I need to add some requests to the queue depending on data from a previous request so I thought I would just loop over an array and add new axois promises to the p-queue according to the length of that array, but I keep getting odd errors

I cannot show the code directly, but here is a small example that has the same problem:

var ml = [1, 2, 3, 4]
for (var i = 0; i < ml.length; i++) {
  promq.add(() => axios.get('http://example.org/' + ml[i]))
  .then(response => {
    console.log(response.data)
  })
}

This will correctly enqueue 4 promises and axios will correctly produce 4 http 404 responses, but that is not because it is trying to visit example.org/1, but instead it makes 4 requests for example.org/undefined

Why is this not working?

Mathias Nielsen
  • 1,560
  • 1
  • 17
  • 31
  • log out `i`. It is going to be `4` for each iteration, I'm almost positive. I was just reading the canonical answer on closures and I think you've hit a problem they touched on there. See example 5 in [this answer](https://stackoverflow.com/a/111111/7605753) – Stephen S Aug 18 '17 at 19:18
  • 1
    Change to `for (let i = 0; i < ml.length; i++)` and the problem will disappear. There are hundreds of dups of this type of problem. It's because you are using `i` in a callback that is called sometime later, but the value of `i` has changed BEFORE you use it. – jfriend00 Aug 18 '17 at 19:18

0 Answers0