简体   繁体   中英

Node.js Q promise forEach returning undefined

Using Q for Node.js, I am promising a HTTP request, and upon fulfillment calling another function passing in the response of that HTTP request, that function then iterates over a JSON array from the HTTP requests, builds up a new array, and returns it.

Debugging Reddit.prototype.parseData I can see the HTTP JSON is passed in, and within the for statement I can console.log data as it's been built, but at the end of the foreach I cannot console.log, or return the data object, it returns 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()

As @sholanozie said, you aren't returning anything from parseRedditData . I'm guessing what you want is:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM