Ok I have a JS method that uses Lodash and mongoose to find docs in a Mongoose collection. This looks fine, but it that appears to not finish the callback function before moving on to the next doc to look for. Below is my function:
importParts: function(participants, event_id, done){
_.forEach(participants, function (participant) {
var race = {event_id: event_id, chip_number_64: participant.chip_number_64};
Runner.findOne({contact_id: participant.contact_id}, function (err, doc) {
if (err) {
logger.error('CANNOT FIND AND UPDATE RUNNER BECAUSE OF: ', err);
done(err);
}
logger.info("IN FINDONE");
if (doc === null) {
logger.info("IN FINDONE1");
participant.races = [race];
Runner.create(participant, function (err, row, rowsAffected) {
if (err) {
logger.error('FAILED TO IMPORT PARTICIPANT: ', doc);
logger.error(err);
done(err);
}
logger.info("IN FINDONE2");
});
}
});
};
done(null);
}
For some reason the above code does not honor the callback function and appears to asynchronously return back to the main method that is calling this one. It's as if the callback is not being honored till after a set amount of time or something is happening asynchronously that shouldn't because I have everything wrapped in callbacks. So I am just trying to find out why the callback isn't completing when the query is executed? Also, this still happens even without the forEach
iteration included in above code.