我在让 numNotes 递增时遇到问题。其他一切似乎都工作得很好。
function getNotes(done) {
noteSchema.find({}).exec((err, notes) => {
var numNotes = 0;
async.each(notes, (n, next) => {
userSchema.findById(n.userId, (err, user) => {
if (err || !user) { next(); return; }
var emailsStr = utils.getEmailsString(user.emails);
if (!utils.toSkipEmail(emailsStr)) {
meetingSchema.findById(n.meetingId, function (err, meeting) {
if (meeting.name.displayValue.indexOf('test', 'Test') == -1) {
numNotes++;
}
});
}
next();
})
}, (err, result) => {
console.log(util.format('Total Number of Notes: %d', numNotes));
done(null);
});
});
}
最佳答案
我认为您的 next()
可能会在 numNotes++
运行之前被调用。这是因为 Node.JS 是 non-blocking如果存在异步函数,则不会按顺序运行您的代码。
要查看之前的操作,请在 if(!utils.toSkipEmail(emailsStr))
之后放置一个 console.log('test 1')
,一个 console.log('test 2')
在 if (meeting.name.displayValue.indexOf('test', 'Test') == -1){...}
之后 block ,以及 if(!utils.toSkipEmail(emailsStr)){...}
block 之后的 console.log('test3')
。
要解决您的问题,请尝试以下操作:
if (!utils.toSkipEmail(emailsStr)) {
meetingSchema.findById(n.meetingId, function(err, meeting) {
if (meeting.name.displayValue.indexOf('test', 'Test') == -1) {
numNotes++;
}
next();
});
} else {
next();
}
关于javascript - 递增不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38447495/