0

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

joe69
  • 97
  • 1
  • 7

2 Answers2

2

Your DB calls are running async, that means the view is rendered before the data can be passed to them. 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.

Ravi
  • 1,320
  • 12
  • 19
  • Thanks, but if i more than 2 dbs calls , it get if else if else if else , this is not clean for me? its not possible to return it ? – joe69 Oct 19 '14 at 12:35
  • But if i want more than 2 db calls User.find() ... { else Country.find().. { else Home.find()... { else Pet.find() }}}} this is not beautiful. is this the only way or can i map something or make extra function to get the data? – joe69 Oct 19 '14 at 12:53
  • nest it further as i've nested `Country` under `User`... and why do you want to call same db 2 times? – Ravi Oct 19 '14 at 12:54
2

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

see this answer as an example

Chaining waterline calls with Promises

Community
  • 1
  • 1
Meeker
  • 5,979
  • 2
  • 20
  • 38