I have an array of user emails obtained from the post data. My goal is to find the _id
associated with each email. Here's the for loop I attempted:
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');
However, the output shows:
END
STUDENT: { _id: 5a11e667d7333203337cd9a4,
name: 'Patrick Jacobs',
email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5d2a3433392b3c3c331d31342b38733331">[email protected]</a>',
password: '$2a$10$CiSw/VH1HCaPtW6Sjz0X4.4avVoLsAH6iyF3FhidorahwLt1WDXoC',
__v: 0 }
STUDENT: { _id: 5a0f7dfb64b5a6000417c662,
name: 'Carlo Jacobs',
email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f69597849a999c9795999485cfc7b6919b979f9ad895999b">[email protected]</a>',
password: '$2a$10$fiIosS4Jo5ehuCp3TfltSOnpypPMWSMvzlb7phRWmNGBtDz5W1rCG',
__v: 0 }
The issue is that END
gets printed before the student details. It seems like the for
loop is asynchronous. How can I adjust it to be synchronous?
Thank you in advance!