Node.js Q promise forEach 返回未定义

Node.js Q promise forEach returning undefined

将 Q 用于 Node.js,我承诺一个 HTTP 请求,并且在调用另一个传递该 HTTP 请求的响应的函数时,该函数然后迭代一个 JSON 数组HTTP 请求,构建一个新数组,然后 returns 它。

调试 Reddit.prototype.parseData 我可以看到传入了 HTTP JSON,并且在 for 语句中我可以 console.log data 因为它已经构建,但是在foreach 的末尾我不能 console.log 或 return 数据对象,它 return 未定义

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()

正如@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);
    });
}