Reputation: 3447
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()
Upvotes: 1
Views: 1041
Reputation: 10104
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);
});
}
Upvotes: 2