【发布时间】:2015-04-08 15:58:27
【问题描述】:
我正在编写一个 Node 应用程序,我需要在其中使用 Promise 进行异步调用。
我目前在 promise 的 .then(function()) 中调用了一个 foreach 循环,但是当我返回 foreach 的最终结果时,我什么也得不到。
在 foreach 中我可以 console.log 记录数据的值并检索它,但不能在返回之前的 for 循环之外?
var Feeds = function(){
this.reddit = new Reddit();
}
Feeds.prototype.parseRedditData = function(){
var _this = this;
this.getData(this.reddit.endpoint).then(function(data){
return _this.reddit.parseData(data, q);
});
}
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;
}
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;
data.push(post);
}
return data;
}
【问题讨论】:
-
我在代码的任何地方都没有看到Q的
.then函数或forEach的使用? -
问:调用 Node.js 时是否使用了“--harmony”标志?问:你们有任何错误处理程序(或任何类型的错误检查)吗?
-
this.getData在哪里? -
@BenjaminGruenbaum 更新为
this.getData。不传递任何 `--harmony`` 标志。 -
@JacobClark 您在
parseRedditData中的this.getData之前缺少return。
标签: javascript node.js promise q