【发布时间】:2017-04-12 09:00:07
【问题描述】:
我在两天前就遇到了一个问题,我不知道如何解决它。我在 forEach 上有一个错误,所以我的应用程序运行良好,然后在没有任何解释的情况下停止。
这是发生错误的代码。
var easy = setInterval(function(){
keywords.forEach(function(k) {
tweetModel.find({keyword: k}).sort({date: -1}).limit(20).exec(function(err, data) {
var score = [];
var date = [];
console.log(data);
console.log(err)
data.forEach(function (item) {
score.push(Math.floor(parseFloat(item.score) * 1000) / 1000);
date.push(item.date.getDate()+'/'+parseInt(item.date.getMonth() + 1)+'/'+item.date.getFullYear()+':'+parseInt(item.date.getHours() + 1)+':'+item.date.getMinutes());
tArrayStats[k] = score;
tArrayStats['date'] = date;
});
});
});
io.sockets.emit('stats',tArrayStats);
},3000);
这里抛出错误
data.forEach(function (item)
但我不知道为什么!谢谢你的帮助。
问有控制台日志数据的输出:
编辑工作代码,感谢@Ids van der Zee
var easy = setInterval(function(){
keywords.forEach(function(k) {
tweetModel.find({keyword: k}).sort({date: -1}).limit(20).exec(function(err, data) {
if (data && !err)
{
var score = [];
var date = [];
console.log(data);
console.log(err)
data.forEach(function (item) {
score.push(Math.floor(parseFloat(item.score) * 1000) / 1000);
date.push(item.date.getDate()+'/'+parseInt(item.date.getMonth() + 1)+'/'+item.date.getFullYear()+':'+parseInt(item.date.getHours() + 1)+':'+item.date.getMinutes());
tArrayStats[k] = score;
tArrayStats['date'] = date;
});
}
});
});
io.sockets.emit('stats',tArrayStats);
},3000);
【问题讨论】:
-
那部分前两行你有
console.log(data),它的输出是什么? -
用输出更新了我的帖子,然后当错误下降时,我得到“未定义”。我正在从 twit 接收数据
-
您显示的数据似乎是数组中的对象---> [{}]
标签: javascript node.js error-handling