我有一个使用mongoose的node.js方法,以便返回一些数据,问题是因为我在我的方法中使用了一个回调,所以没有任何东西被返回给客户端
我的代码是:
var getApps = function(searchParam){
var appsInCategory = Model.find({ categories: searchParam});
appsInCategory.exec(function (err, apps) {
return apps;
});
}
如果我试图通过使用json对象同步执行它,例如它将起作用:
var getApps = function(searchParam){
var appsInCategory = JSONOBJECT;
return appsInCategory
}
我该怎么办?
答案 0 :(得分:5)
您无法从回调中退回 - 请参阅this canonical about the fundamental problem。既然您正在使用Mongoose,那么您可以回复它的承诺:
var getApps = function(searchParam){
var appsInCategory = Model.find({ categories: searchParam});
return appsInCategory.exec().then(function (apps) {
return apps; // can drop the `then` here
});
}
可以让你这样做:
getApps().then(function(result){
// handle result here
});