【发布时间】:2015-02-10 05:12:14
【问题描述】:
将 Q 用于 Node.js,我承诺一个 HTTP 请求,并在调用另一个函数传递该 HTTP 请求的响应时,该函数然后从 HTTP 请求中迭代一个 JSON 数组,建立一个新数组, 并返回它。
调试Reddit.prototype.parseData 我可以看到传入了HTTP JSON,并且在for 语句中我可以console.log data 因为它已经构建,但在foreach 结束时我不能console.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()
【问题讨论】:
-
您的
parseRedditData方法将始终未定义,因为它不返回任何内容。当getData承诺得到解决时,通过记录data变量,您将看到您期望的结果(假设您的代码中没有其他错误)。 -
更新代码以从承诺中返回某些内容,getData 承诺上的
data变量是 http 请求的结果? -
顺便说一句,您应该在
for(var i = 0; i <= dataLength; i++)中使用<运算符 inReddit.prototype.parseData
标签: javascript node.js http promise q