0

感谢您的关注,我被困在代码中,我不是一个真正出色的 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);
4

2 回答 2

1

与任何事情一样,您需要在调用之前制作一份副本@client.connect()

query: (sql) ->
  client = @client
  @client.connect (err) ->
    @client.query 'SELECT NOW() AS "theTime"', (err, result) ->
        client.close()
        return result.rows[0].theTime

在 JavaScript 中:

Database.prototype.query = function(sql) {
    var client = this.client;

    return this.client.connect(function(err) {
      return this.client.query('SELECT NOW() AS "theTime"', function(err, result) {
        client.close();
        return result.rows[0].theTime;
      });
    });
};
于 2013-07-04T23:30:57.060 回答
1

尝试使用范围解析运算符调用原型方法: Database::close();

等效的 CoffeeScript 将是:

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) ->
          Database::close()
          result.rows[0].theTime
于 2013-07-04T23:34:15.440 回答