How to return a Node.js callback
I have a node.js method that is using mongoose to return some data, the problem is that since I am using a callback inside my method, nothing is returned to the client
my code:
var getApps = function(searchParam){
var appsInCategory = Model.find({ categories: searchParam});
appsInCategory.exec(function (err, apps) {
return apps;
});
}
If I try to do it synchronously with a json object, for example, it works:
var getApps = function(searchParam){
var appsInCategory = JSONOBJECT;
return appsInCategory
}
What can I do?
+3
source to share
1 answer
You cannot return from a callback - see this canonical information for a fundamental issue . Since you are working with Mongoose, you can return a promise to it:
var getApps = function(searchParam){
var appsInCategory = Model.find({ categories: searchParam});
return appsInCategory.exec().then(function (apps) {
return apps; // can drop the `then` here
});
}
What would you do:
getApps().then(function(result){
// handle result here
});
+5
source to share