The findOne method is an asynchronous method that waits for a response before executing its callback. In your case immediately the for loop
starts the asynchronous call is executed first, however because the response isn't received yet, the code continues with the line with code console.log("first")
. After it receives a receives a response from the findOne it executes whatever code is in the callback.
To get the line to execute before the code in the callback try any of these 2
router.post("/path", function(req, res, next) {
console.log("first")
for(var i = 0; i < req.body.getname.length; i++) {
Bun.findOne({title: req.body.getname[i]}, function(err, data) {
console.log("second");
});
}
});
OR
router.post("/path", function(req, res, next) {
for(var i = 0; i < req.body.getname.length; i++) {
Bun.findOne({title: req.body.getname[i]}, function(err, data) {
//Bring that line first
console.log("first");
console.log("second");
});
}
}