3

I have a node.js method that using mongoose in order to return some data, the problem is that since I'm using a callback inside my method nothing is being returned to the client

my code is:

var getApps = function(searchParam){
    var appsInCategory = Model.find({ categories: searchParam});
    appsInCategory.exec(function (err, apps) {
        return apps;
    });
}

If I'm trying to do it synchronously by using a json object for example it will work:

var getApps = function(searchParam){
    var appsInCategory = JSONOBJECT;
    return appsInCategory
} 

What can I do?

1 Answer 1

5

You can't return from a callback - see this canonical about the fundamental problem. Since you're working with Mongoose you can return a promise for it though:

var getApps = function(searchParam){
    var appsInCategory = Model.find({ categories: searchParam});
    return appsInCategory.exec().then(function (apps) {
        return apps; // can drop the `then` here
    });
}

Which would let you do:

getApps().then(function(result){
    // handle result here
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.