我从帖子数据中获取了一系列用户电子邮件。我想找到与每封电子邮件相关的_id
。我尝试了这个循环:
var studentIds = [];
for (var i = studentEmails.length - 1; i >= 0; i--) {
var email = studentEmails[i];
User.findOne({"email": email}, (err, student) => {
if (err) {
console.log("ERROR" + err);
}
if (student) {
var id = student._id;
studentIds.push(id);
console.log("STUDENT: " + student);
}
});
}
// Outside for loop
console.log('END');
但是,这会记录以下内容:
END
STUDENT: { _id: 5a11e667d7333203337cd9a4,
name: 'Patrick Jacobs',
email: 'windvaan@live.nl',
password: '$2a$10$CiSw/VH1HCaPtW6Sjz0X4.4avVoLsAH6iyF3FhidorahwLt1WDXoC',
__v: 0 }
STUDENT: { _id: 5a0f7dfb64b5a6000417c662,
name: 'Carlo Jacobs',
email: 'carlojacobs91@gmail.com',
password: '$2a$10$fiIosS4Jo5ehuCp3TfltSOnpypPMWSMvzlb7phRWmNGBtDz5W1rCG',
__v: 0 }
如您所见,首先打印END
。我不希望这样。我假设for
循环是异步的?我怎样才能使它同步?
答案 0 :(得分:0)
这不是for
循环,而是异步的User.findOne
调用。
关注this answer,您可以使用streamline.js;尝试以下操作使呼叫同步。
var result = User.findOne({"email": email}, _);
if (result === null) {
console.log("ERROR" + err);
}
var id = result._id;
studentIds.push(id);
console.log("STUDENT: " + result);
答案 1 :(得分:0)
解决方案是
var studentIds = [];
var loopRecords = function (records, cb) {
if (!records.length) return cb();
var email = records.shift();
User.findOne({"email": email}, (err, student) = > {
if (err) {
console.log("ERROR" + err);
}
if (student) {
var id = student._id;
studentIds.push(id);
console.log("STUDENT: " + student);
}
return loopRecords(records, cb);
}
}
loopRecords(studentEmails,function () {
console.log('END');
})