node.js 使用 Q(承诺)的变量上下文问题

Variable context issue on node.js using Q (promise)

我正在使用 node.js 和 Q 作为承诺实现。

出于某种原因,我必须用循环构建一些 promise。当然,在“真实”代码中,我不在“for”循环中使用常量。

我在将 i 作为函数 buildPromiseForIdx 的参数时遇到问题。我期望传递 i 的值并期望在控制台中得到以下结果。

-3
*3

但代码显示:

-3
*2

代码如下:

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)}));
}

以下问题的答案也适用于这种情况。

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

我的循环现在是:

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);
}