0

I have to call some code asynchronous code in a loop. I tried using promises, but the iterator is not being bound as I would expect. When I do something like

for n in [1,2,3]
  console.log "PRINT:" + n
  Q()
  .then =>
    console.log "PRINT:" + n

It prints

PRINT:1
PRINT:2
PRINT:3
PRINT:3
PRINT:3
PRINT:3

I understand that this is because the loop is executed first and then the promises start to resolve. I'd like to know how to get each print inside the promise chain to be called with a different value of n (or any way to get a promise chain to execute for different values in an array).

EDIT: as requested in the comments, my code in JS looks like this

var n, _i, _len, _ref;

_ref = [1, 2, 3];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  n = _ref[_i];
  console.log("PRINT:" + n);
  Q().then((function(_this) {
    return function() {
      return console.log("PRINT:" + n);
    };
  })(this));
}
Martin Epsz
  • 842
  • 1
  • 8
  • 16

0 Answers0