-2

I'm trying to call getMarchandiseList() method that call a mongoose method " find({}) " in my marchandise router. the problem is when I send the responce I find that I get a result=0 before the find({}) method send it's result //the result should be {id_marchandise : 01 , libelle_marchandise : 'fer'}.

[MarchandiseDAO.js][1]

*

var express = require("express");
var router = express.Router();
var marchandiseDAO = require ('../DAO/marchandises');
router.get('/listmarchandise',  function (req,res) {

    var marchandise  = new marchandiseDAO();
    marchandise.getMarchandiseList();
    res.send("result" +marchandise.result);

});
module.exports = router;

*

[marchandiserouter.js][2]

 var model = require("../Models/model");

var marchandiseDAO = function () {

    console.log("get instance ");
    this.result = 0 ;

}

marchandiseDAO.prototype.getMarchandiseList = function () {

    console.log("begin");

    model.MarchandiseModel.find({},function(err,marchandiselist){

        console.log("traitement");

        if(err)  result = err;

        else  result = marchandiselist;
    });

    console.log("end");

}
4
  • 2
    post code, not screenshots of code Commented Mar 20, 2017 at 15:32
  • @SergioTulentsev It always amazes me when people post screenshots here. It's so much easier to copy and paste code than to post screenshots and yet they go out of their way to post their code in the only form that no one can fix. I don't think I've seen posting screenshots even a year or two ago and now everyone is doing it, I wonder why. Commented Mar 20, 2017 at 15:36
  • @rsp: there is a lot of really easy-to-use screenshot tools. You press a button/hotkey and -bam- you have a url with your screenshot, already in your clipboard. Commented Mar 20, 2017 at 15:48
  • thanks for your advice , it's the first time for me so I do not know maybe the correct way to post my problem Commented Mar 20, 2017 at 18:26

1 Answer 1

2

You cannot run mongoose methods synchronously. But if you use a modern version of Node then you can make it appear as if it was run asynchronously.

Unfortunately you posted your code examples as screenshots which would require me to use Photoshop to fix your code, which is obviously not worth the hassle. So instead I will show you a general solution.

Using normal promises:

Model.find({...}).then(data => {
  // you can only use data here
}).catch(err => {
  // always handle errors
});

Using await:

try {
  let data = await Model.find({...});
  // you can only use data here
} catch (err) {
  // always handle errors
}

The second example can only be used in an async function. See this for more info:

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.