【问题标题】:Accessing the promise object from within the then function从 then 函数中访问 promise 对象
【发布时间】:2015-02-20 15:29:04
【问题描述】:

我正在使用 node.js 的 Q 库。我正在尝试打印一份报告,该报告将打印查询名称和结果。这就是我所拥有的。代码打印“In function undefined 。如何从“then”函数中访问 promise 对象的值?

var queries = ["2091 OR 2092 OR 2093", 
            "2061 OR 2062",
            "2139 OR 2140 OR 2141"
            ];

var promises = new Array();
for (var i=0; i<queries.length; i++) {
    promises[i]=performSearch(queries[i]);
    promises[i].query = queries[i];
    console.log("Outside function ", promises[i].query);

    promises[i].then(function(data) {
            console.log("In function ", this.query);
            processSearchResults(data,this.query);
    });
}
Q.allSettled(promises).then(function(results) {
    endFunction();
});

【问题讨论】:

  • 如果performSearch返回一个promise,那么data也是一个promise。
  • @BenFortune: data 不是承诺 - 根据规范,它不得是承诺?
  • @BenFortune 数据不是承诺。我已经在 promise 对象上设置了查询属性。我想从 then 函数中访问这个属性

标签: node.js asynchronous scope promise q


【解决方案1】:

这就是我所拥有的:

promises[i].then(function(data) {
        console.log("In function ", this.query);
        processSearchResults(data,this.query);
});

代码打印“In function undefined”。

The spec 要求调用回调时没有任何 this 值,因此 this 将在草率模式下引用全局 (window) 对象,该对象没有 .query 属性。在严格模式下,当 thisundefined 时,您会遇到异常。

如何从“then”中访问 promise 对象的值 功能?

没有特殊的方法。您通常不需要将 Promise 作为对象访问,它只是表示异步计算的单个结果的透明值。你需要做的就是调用它的.then() 方法——在回调内部,没有理由访问promise 对象,因为你已经可以访问它所持有的信息(data,事实上调用了履行回调)。

因此,如果您想访问您的 .query 属性,则必须照常使用 promises[i]。但是,you will need a closure 代表 i,所以无论如何你最好还是使用 map 并将 query 字符串直接保存在闭包中,而不是将其作为 Promise 对象的属性:

var queries = ["2091 OR 2092 OR 2093", 
            "2061 OR 2062",
            "2139 OR 2140 OR 2141"
            ];

var promises = queries.map(function(query) {
    var promise = performSearch(query);
    console.log("Outside function ", query);
    var processedPromise = promise.then(function(data) {
        console.log("In function ", query);
        return processSearchResults(data, query);
    });
    return processedPromise; // I assume you don't want the unprocessed results
});
Q.allSettled(promises).then(function(processedResults) {
    endFunction(processedResults);
});

【讨论】:

  • 谢谢。按预期工作。
猜你喜欢
  • 1970-01-01
  • 2018-06-25
  • 1970-01-01
  • 1970-01-01
  • 2018-06-12
  • 1970-01-01
  • 1970-01-01
  • 2015-07-01
  • 2015-11-12
相关资源
最近更新 更多