gpt4 book ai didi

node.js - Node postgres 'event emitter style' 与 'callback style'

转载 作者:搜寻专家 更新时间:2023-10-31 23:29:15 25 4
gpt4 key购买 nike

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 通过 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();

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

最佳答案

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());
});

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

关于node.js - Node postgres 'event emitter style' 与 'callback style',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12012126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com