對Node.js使用Q,我承諾會有一個HTTP請求,並且在履行時調用另一個傳遞該HTTP請求的響應的函數,然後該函數將遍歷來自HTTP請求,建立一個新的數組,並返回它。Node.js Q promise for each return undefined
調試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承諾時記錄數據變量,您將看到您期望的結果(假設代碼中沒有其他錯誤)。 – soulprovidr 2015-02-09 21:09:33
更新的代碼返回promise中的某些內容,getData promise上的'data'變量是http請求的結果? – 2015-02-09 21:11:41
另一方面,您應該在'Reddit.prototype.parseData'中爲'(var i = 0; i <= dataLength; i ++)'中的'<'運算符' – vanchagreen 2015-02-09 21:16:12