Node.js Q承诺每次返回undefined

时间:2015-02-09 21:05:39

标签: javascript node.js http promise q

对Node.js使用Q,我承诺一个HTTP请求,并且在执行调用另一个函数传递该HTTP请求的响应时,该函数然后从HTTP请求迭代JSON数组,构建一个新数组,并将其返回。

调试Reddit.prototype.parseData我可以看到HTTP JSON被传入,并且在for语句中我可以在它构建时使用console.log data,但是在foreach结束时我无法控制。 log,或返回数据对象,它返回undefined

Reddit.js

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;

        console.log(data); //returns data    

        data.push(post);
    }

    console.log(data); // returns undefined

    return data;
}

module.exports = Reddit;

Feeds.js

var https   = require('https'),
        q       = require('q'),
        Reddit  = require('./sources/reddit');

var Feeds = function(){
    this.reddit = new Reddit();
    console.log(this.parseRedditData()); //undefined
}

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

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

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


}

var fe = new Feeds()

1 个答案:

答案 0 :(得分:2)

正如@sholanozie所说,你没有从parseRedditData返回任何内容。我猜你想要的是:

var Feeds = function(){
    this.reddit = new Reddit();
    this.parseRedditData().then(function(data) {
        console.log(data);
    });
};
...
Feeds.prototype.parseRedditData = function(){
    var _this      = this;

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