2015-01-16 65 views
0

後得到的數據我有一個問題,當從Postgres的 這是我的代碼段分配數據:如何爲類的屬性分配數據從Postgres的

var database = function() { 
    client.connect(function(err) { 
     if(err) { 
      return console.error('could not connect to postgres', err); 
     } 
    }); 
}; 

database.prototype.getData = function() { 
    this.data = []; 
    this.queryStr = 'SELECT * FROM "agents"'; 
    this.query = client.query(this.queryStr); 
    var data = []; 
    this.query.on('row', function(row) { 
     data.push(row); 
     //console.log(data); // get data successfully 
    }); 

    //could not assign data 
    console.log(data); // but when go out above function, data become no value 
    this.data = data; // and then I can not assign it for property of class (like this.data) 
}; 

誰能幫我解決this.sorry我的英語水平。 Tks很多。

回答

1

您的數據分配在您的方法運行後執行的回調中。

通常當你的函數執行結束時你會傳遞一個回調函數。

我不擅長使用p​​ostgre庫,但這裏有一個僞代碼:

database.prototype.getData = function(success) { 
    this.data = []; 
    this.queryStr = 'SELECT * FROM "agents"'; 
    this.query = client.query(this.queryStr); 
    var self = this; 
    var data = []; 
    this.query.on('row', function(row) { 
     data.push(row); 
     //console.log(data); // get data successfully 
    }); 
    this.query.on('end', function() { //when the query executes succesfully 
     self.data = data; 
     success(); //call success callback or perform other actions 
    }); 
}; 
+0

謝謝您的回答,但它仍然不是在外面有功能價值。它實際上是.on('end',函數)。 –

+0

在任何情況下,它都不會具有任何值以外的值 –

+0

但我想將它分配給類屬性,因此我可以在該Object中使用該數據。 –