js 现在我的 app.js 遇到问题 问题是我想在执行路由根之前调用一个函数 我要调用的函数如下:
function findCats(){
var cats;
Categorie.find({}, function(err, foundCats){
if(err){
console.log("Error can not find the categories ==> "+err);
}else{
this.cats = foundCats;
}
});
return this.cats;
}
它从数据库中查找类别并发送返回结果 路由根应该在执行 res.render() 之前使用此结果 这是我的路线根
app.get("/",function(req, res){
res.render("landing",{cats: findCats()});
});
提前致谢!
最佳答案
向 findCats 函数添加回调
function findCats(callback) {
var cats;
Categorie.find({}, function(err, foundCats){
if (err) {
console.log("Error can not find the categories ==> " + err);
} else {
callback(foundCats);
}
});
}
然后在该回调中发送您的响应
app.get("/",function(req, res){
findCats((cats) => {
res.render("landing", {cats});
});
});
关于javascript - 在 Node.js 中使用回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47569868/