感谢您的关注,我被困在代码中,我不是一个真正出色的 javascript 开发人员,并且我在创建数据库类时遇到了困难,我的问题是我尝试使用的方法的范围并将 postgre 连接封装在一个班级:
Connector = new require('./connector.js').Connector
PGClient = new require('pg').Client
exports.Database =
class Database
constructor:(@connector)->
@connector = Connector if not @connector
@client = new PGClient( @connector.connection_string );
@client.connect()
close: ->
@client.end()
query: (sql) ->
@client.connect (err) ->
@client.query 'SELECT NOW() AS "theTime"', (err, result) ->
return result.rows[0].theTime
#output: Tue Jan 15 2013 19:12:47 GMT-600 (CST)
在查询方法中我建立了一个连接,然后在连接回调中我想使用@client对象的查询,我想在return语句之前调用close方法,但是这样,在我没有的回调中访问对象范围。
有没有办法做到这一点?
javascript中的代码
(function() {
var Connector, Database, PGClient;
Connector = new require('./connector.js').Connector;
PGClient = new require('pg').Client;
exports.Database = Database = (function() {
function Database(connector) {
this.connector = connector;
if (!this.connector) {
this.connector = Connector;
}
this.client = new PGClient(this.connector.connection_string);
console.log(this.client);
this.client.connect();
}
Database.prototype.close = function() {
return this.client.end();
};
Database.prototype.query = function(sql) {
return this.client.connect(function(err) {
return this.client.query('SELECT NOW() AS "theTime"', function(err, result) {
return result.rows[0].theTime;
});
});
};
return Database;
})();
}).call(this);