使用Q for Node.js,我向一个HTTP请求承诺,并在实现时调用另一个函数以传递该HTTP请求的响应,然后该函数从HTTP请求遍历JSON数组,建立一个新数组,然后返回它。
调试中,Reddit.prototype.parseData
我可以看到传入了HTTP JSON,并且在for语句中,可以data
在构建它时进行console.log ,但是在foreach的末尾,我无法console.log或返回数据对象,它返回未定义的
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);
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句