Michael Bates
Michael Bates

Reputation: 1934

Wait for Mongoose Query to Finish

Say I have the following code:

function MyClass(id, x, y, z) {
    var self = this;
    MyModel.findByID(id, function(err, model) {
        if(err) { // Do something }
        self.model = model
    });
    this.x = x;
    this.y = y;
    this.z = z;
}

MyClass.prototype.myMethod = function() {
    console.log(this.model.id);
}

var obj = new MyClass(123, 7, 8, 9);
obj.myMethod();

How can I ensure that this.model is set in myMethod, since Mongoose queries are asyncronous. Or am I programming in a 'non' NodeJS way?

Thanks

Upvotes: 1

Views: 4524

Answers (1)

hexacyanide
hexacyanide

Reputation: 91619

You could pass a callback that would run when the database query has ended, and the target variable has been assigned a value:

function MyClass(id, x, y, z, fn) {
  var self = this;

  this.x = x;
  this.y = y;
  this.z = z;

  MyModel.findByID(id, function(err, model) {
    self.model = model
    fn.call(self);
  });
};

MyClass.prototype.myMethod = function() {
  console.log(this.model.id);
};

Then to use it:

var obj = new MyClass(123, 7, 8, 9, function() {
  obj.myMethod();
});

Upvotes: 1

Related Questions