当前位置 : 主页 > 网页制作 > Nodejs >

node.js – node-postgres’事件发射器样式’vs’回调样式’

来源:互联网 收集:自由互联 发布时间:2021-06-16
node-postgres声明如下: node-postgres supports both an ‘event emitter’ style API and a ‘callback’ style. The callback style is more concise and generally preferred, but the evented API can come in handy. They can be mixed and m
node-postgres声明如下:

node-postgres supports both an ‘event emitter’ style API and a ‘callback’ style. The
callback style is more concise and generally preferred, but the evented API can come in
handy. They can be mixed and matched.

使用事件发射器API,我可以执行以下操作:

var db = new pg.Client("insert-postgres-connection-info");
db.connect();

然后我可以使用db在我的web应用程序中使用db.query(‘sql statement here’)执行查询.使用回调样式,每次我想运行查询时都会执行以下操作:

pg.connect(conString, function(err, client) {
  client.query("sql statement", function(err, result) {
    // do stuff
  });
});

所以我的问题是为什么使用回调样式“通常更喜欢”?每次使用数据库执行某些操作时打开连接效率不高吗?使用回调样式有什么好处?

编辑

我可能会错误地认为他的意思是“回调风格”(我不是在开玩笑,我的JavaScript不是很强)但我的问题是关于连接方法.我假设以下是回调样式连接方法:

// Simple, using built-in client pool

var pg = require('pg'); 
//or native libpq bindings
//var pg = require('pg').native

var conString = "tcp://postgres:1234@localhost/postgres";

//error handling omitted
pg.connect(conString, function(err, client) {
  client.query("SELECT NOW() as when", function(err, result) {
    console.log("Row count: %d",result.rows.length);  // 1
    console.log("Current year: %d", result.rows[0].when.getYear());
  });
});

以下是EventEmitter API连接方法:

// Evented api
var pg = require('pg'); //native libpq bindings = `var pg = require('pg').native`
var conString = "tcp://postgres:1234@localhost/postgres";

var client = new pg.Client(conString);
client.connect();

如果我只是在这里混淆了条款,我的问题仍然存在. pg.connect(do queries)每次使用它时都会打开一个新连接(不是吗?)

var client = new pg.Client(conString);
client.connect();

打开一个连接,然后允许您在必要时使用客户端运行查询,不是吗?

EventEmitter样式更适用于此类事物:

var query = client.query("SELECT * FROM beatles WHERE name = $1", ['John']);
query.on('row', function(row) {
  console.log(row);
  console.log("Beatle name: %s", row.name); //Beatle name: John
  console.log("Beatle birth year: %d", row.birthday.getYear()); //dates are returned as javascript dates
  console.log("Beatle height: %d' %d\"", Math.floor(row.height/12), row.height%12); //integers are returned as javascript ints
});

通过混合和匹配,您应该能够执行以下操作:

// Connect using EE style
var client = new pg.Client(conString);
client.connect();

// Query using callback style
client.query("SELECT NOW() as when", function(err, result) {
  console.log("Row count: %d",result.rows.length);  // 1
  console.log("Current year: %d", result.rows[0].when.getYear());
});

请注意,即使使用回调样式,每次要执行查询时也不会打开连接;最有可能的是,您在应用程序启动时打开连接并在整个过程中使用它.

网友评论