简体   繁体   English

Sailsjs find()回调操作

[英]Sailsjs find() callback action

i have a problem with my callbacks, i dont know how i get it back. 我的回调有问题,我不知道该如何找回。

index: function(req, res,next) {
    User.find().exec(function(err,users) {
        if(err) {
         //do something
        }
        res.locals.users = users
        return true;
    });

   Country.find().exec(function(err,countrys) {
    //save country
   }

  console.log(res.locals.users)
  res.view({
     users: res.locals.users,
     country: countrys
     user:res.locals.user
  });
}

How can i get access to both objects? 我怎样才能访问两个对象?

Thank you 谢谢

Your DB calls are running async , that means the view is rendered before the data can be passed to them. 您的数据库调用正在运行async ,这意味着在将数据传递给视图之前先呈现视图。 So you have to make them in synchronous manner. 因此,您必须使其同步。 This can be achived via callback or you can chain your functions instead of callbacks, like this, 可以通过回调来实现,也可以链接函数而不是回调,就像这样,

index: function(req, res,next) {
   User.find().exec(function(err,users) {
    if(err) {
     //do something
    }
    else{
      res.locals.users = users
      Country.find().exec(function(err,countrys) {
       if(err) {
           //do something
       }
       else{
           console.log(res.locals.users)
           res.view({
             users: res.locals.users,
             country: countrys
             user:res.locals.user
           });
       }
      }
    }
  });
}

Other way is to use callbacks. 其他方法是使用回调。

If your trying to make it pretty and organised when you keep adding more queries you can use the async library that comes with sails 如果您在不断添加更多查询时尝试使其美观且井井有条,则可以使用Sails附带的异步库

see this answer as an example 以这个答案为例

Chaining waterline calls with Promises 用承诺链接水线电话

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM