0

I need to use data that was recieved in a asynchronous way in a model 'toObject' method.

toObject: function() {
    var user = this;
    return q(Group.find())
    .then(function(groups) {
    ....
    return user;
    });
},
toJSON: function() {
    this.toObject().then(function(user) {
        return user;
    });
}

This does not work and breaks all the policies (user becomes unavailable).

Is there a way in which I could do this ? Thanks.

  • Looks like this question http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call, not SailsJS specific. – elclanrs Nov 30 '13 at 07:35

1 Answers1

0

Sails doesn't wait for toJSON to finish. It assumes that this method isn't async. Place for this kind of logic is inside controller. In for example beforeCreate method you have to call last param which is function and usually called next() to move further because sails waits for that.

beforeCreate: function (values, next) {
    bcrypt.hash(values.password, 10, function(err, encryptedPassword){
        values.password = encryptedPassword;
        next();
    })
}
Paweł Wszoła
  • 1,096
  • 1
  • 9
  • 21