javascript - 在 Node.js 中使用回调

标签 javascript 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});
     });
 });

关于javascript - 在 Node.js 中使用回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47569868/

相关文章:

javascript - 我怎样才能在我的javascript中获得以KM为单位的总距离

javascript - Select2 使用 tags = true 自动选择第一个选项

node.js - Node + Elasticsearch : Sending a body on a GET request?

node.js - 将 Edge.JS 与 Electron 结合使用失败

node.js - Node.js 中的异步或步骤

javascript - 服务后和更新时 Angular 4 CLI 太慢

node.js - 来自填充模型的 Mongoose 随机和混合响应

javascript - Owl Carousel : change slide on hover dots

javascript - 主干 View 的默认值

javascript - 如何在不打开另一个窗口的情况下在屏幕上弹出图像