Loopback: validateAsync timeouts the server

Created on 16 Jul 2015  路  5Comments  路  Source: strongloop/loopback

I have an async validation in one of my models in which I query for a related object to validate it's existence. The problem is that the request is timing out on this validation and the server never responds.

`````` js
module.exports = function(Ip) {
// Required fields
Ip.validatesPresenceOf('server_id');

  ...

  Ip.validateAsync('server_id', isExistingServer, {
        message: 'invalid server'
  });

  function isExistingServer(err, done) {
        var ServerModel = Ip.app.models.Server;
        var self = this;
        process.nextTick(function() {
              ServerModel.findById(self.server_id, function(e, server) {
                    console.log(_.isNull(server));// this actually prints false
                    return _.isNull(server) ? err() : done();
              });
        });
  }

};```
``````

Most helpful comment

Hey, was also wondering why done() would return correctly and err() would not.
The answer is that done() works as a callback kick-off, just like next(). So always call it last.

  Model.validateAsync('userId', function(err, done) {
    OtherModel.exists(this.userId, function(_, exists) {
      if (!exists) err() // if err() is called, the response will be a ValidationError
      done() // always call this last, just like next() 
    })
  })

All 5 comments

Hey, was also wondering why done() would return correctly and err() would not.
The answer is that done() works as a callback kick-off, just like next(). So always call it last.

  Model.validateAsync('userId', function(err, done) {
    OtherModel.exists(this.userId, function(_, exists) {
      if (!exists) err() // if err() is called, the response will be a ValidationError
      done() // always call this last, just like next() 
    })
  })

hey @ciokan do you still have problem with callback function?
I think @Discountrobot 's answer makes sense, if it doesn't solve your problem, could you fork sandbox and replace it with your code? Then I can debug with your code. Thanks!

Hi, I can confirm that @Discountrobot 's answer is working for me. Thanks @Discountrobot!
IMHO the api docs are not that clear at this point.

@steirico Good to know that your problem is solved and thanks for your suggestion. I am closing it to keep issues clear for feature and bug. Please feel free to reopen it if you have other questions.

Nice one. Thanks for that. done() always need to be called.

Was this page helpful?
0 / 5 - 0 ratings