0

I'm using node.js with Q as promise implementation.

For some reason I have to build a few promise with a loop. In the "real" code, of course, I do not use constant in "for" loop.

I have an issue when I give i as parameter to my function buildPromiseForIdx. I expect to pass the value of i and expect the following result in the console.

-3
*3

but the code displays:

-3
*2

Here is the code:

function loop(promise, fn) {
  return promise.then(fn).then(function (result) {
    return !result ? loop(Q(result), fn) : result;
  });
}

function buildPromiseForIdx(i) {
  return getIdx(i*10).then(parseIdx);
}

// building promises for all idx page
var promises= [];
for (var i = 3 ; i >= 3 ; i--) {
  log.debug('-'+i);
  promises.push(loop(Q(false), function () { log.debug('*'+i);return buildPromiseForIdx(i)}));
}
Suciu Andrei
  • 131
  • 4
aligot
  • 259
  • 2
  • 7
  • Hum... I'll try something like this: http://stackoverflow.com/questions/2568966/how-do-i-pass-the-value-not-the-reference-of-a-js-variable-to-a-function – aligot Apr 27 '15 at 13:00

1 Answers1

1

The answer of the following question is also working in this case.

How do I pass the value (not the reference) of a JS variable to a function?

My loop is now:

var promises= [];
for (var i = 3 ; i >= 3 ; i--) {
  log.debug('-'+i);
  (function (i) {
    promises.push(loop(Q(false), function () { log.debug('*'+i);return buildPromiseForIdx(i)}));
  })(i);
}
Community
  • 1
  • 1
aligot
  • 259
  • 2
  • 7