【问题标题】:Node.js promises using QNode.js 承诺使用 Q
【发布时间】:2015-04-08 15:58:27
【问题描述】:

我正在编写一个 Node 应用程序,我需要在其中使用 Promise 进行异步调用。

我目前在 promise 的 .then(function()) 中调用了一个 foreach 循环,但是当我返回 foreach 的最终结果时,我什么也得不到。

在 foreach 中我可以 console.log 记录数据的值并检索它,但不能在返回之前的 for 循环之外?

var Feeds = function(){
    this.reddit = new Reddit();
}

Feeds.prototype.parseRedditData = function(){
    var _this      = this;

    this.getData(this.reddit.endpoint).then(function(data){
        return _this.reddit.parseData(data, q);
    });
}

Feeds.prototype.getData = function(endpoint){
    var deferred = q.defer();

    https.get(endpoint, function(res) {
        var body = '';

        res.on('data', function(chunk) {
            body += chunk;
        });

        res.on('end', function() {
           deferred.resolve(JSON.parse(body));
        });
    }).on('error', function(e) {
        deferred.reject(e);
    });

    return deferred.promise;
}

var Reddit = function(){
    this.endpoint = "https://www.reddit.com/r/programming/hot.json?limit=10";
}

Reddit.prototype.parseData = function(json, q){
    var dataLength  = json.data.children.length,
        data        = [];

    for(var i = 0; i <= dataLength; i++){
        var post    = {};

        post.url    = json.data.children[i].data.url;
        post.title  = json.data.children[i].data.title;
        post.score  = json.data.children[i].data.score;

        data.push(post);
    }


    return data;
}

【问题讨论】:

  • 我在代码的任何地方都没有看到Q的.then函数或forEach的使用?
  • 问:调用 Node.js 时是否使用了“--harmony”标志?问:你们有任何错误处理程序(或任何类型的错误检查)吗?
  • this.getData在哪里?
  • @BenjaminGruenbaum 更新为 this.getData。不传递任何 `--harmony`` 标志。
  • @JacobClark 您在parseRedditData 中的this.getData 之前缺少return

标签: javascript node.js promise q


【解决方案1】:
Feeds.prototype.parseRedditData = function(){
    var _this      = this;

    this.getData(this.reddit.endpoint).then(function(data){
        return _this.reddit.parseData(data, q);
    });
}

当我看到这个时,我在 promise 的回调中看到一个“return”...我不知道你为什么要这样做,但我只是想确定一下:

我希望这个“返回”是函数 'parseRedditData' 的返回值,这是行不通的。

在此处返回数据的唯一方法是使用回调或承诺,如下所示:

Feeds.prototype.parseRedditData = function(callack){
    var _this      = this;

    this.getData(this.reddit.endpoint).then(function(data){
        callback(_this.reddit.parseData(data, q));
    });
}

【讨论】:

    猜你喜欢
    • 2015-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-15
    • 2015-02-25
    • 2015-05-12
    • 2015-06-22
    • 1970-01-01
    相关资源
    最近更新 更多