[英]using callback with node.js
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});
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.