从自制的数据库类中查询

时间:2013-07-04 23:19:18

标签: javascript coffeescript scope anonymous-function

感谢关注,我被困在一个代码中,我不是一个非常棒的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);

2 个答案:

答案 0 :(得分: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;
      });
    });
};

答案 1 :(得分:1)

尝试使用范围解析运算符调用prototype方法: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