0

I dont understand why the command at the bottom gets executed before the code in the mongoose/function.

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) {
          console.log("second")
       })
    }
    console.log("first")
})
Shilloko
  • 15
  • 4

1 Answers1

0

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");
        });
    }
}
Xixis
  • 881
  • 6
  • 8
  • Okay do you have an idea on how to fix it? Or an alternative? – Shilloko Aug 25 '18 at 22:58
  • It is not an error. What you should rather do is put the `console.log("first")` code before the `console.log("second")` but all in the callback. So all will execute after the request gets a response. – Xixis Aug 25 '18 at 23:43