【问题标题】:Variable context issue on node.js using Q (promise) [duplicate]使用 Q(promise)的 node.js 上的变量上下文问题 [重复]
【发布时间】:2015-07-05 22:33:34
【问题描述】:

我正在使用带有 Q 的 node.js 作为 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)}));
}

【问题讨论】:

标签: javascript node.js promise q


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2016-12-10
    • 1970-01-01
    • 2013-12-16
    • 1970-01-01
    • 2019-01-17
    • 2020-06-16
    • 1970-01-01
    • 2015-12-31
    • 2020-03-11
    相关资源
    最近更新 更多