2013-12-12 92 views
1

說我有下面的代碼:等待貓鼬查詢結束

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(); 

我怎樣才能確保this.modelmyMethod設置,因爲貓鼬查詢是asyncronous。還是我用'非'NodeJS方式編程?

感謝

回答

1

你可以通過在數據庫查詢已經結束,將運行一個回調,目標變量已經被賦值:

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); 
}; 

然後使用它:

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

很明顯,謝謝 –