node-postgres states the following:
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.
With the event emitter API, I can do the following:
var db = new pg.Client("insert-postgres-connection-info");
db.connect();
And then I can use db to execute queries throughout my web app using db.query('sql statement here'). With the callback style, I would do the following each time I want to run a query:
pg.connect(conString, function(err, client) {
client.query("sql statement", function(err, result) {
// do stuff
});
});
So my question is why is it “generally preferred” to use the callback style? Isn’t it inefficient to open a connection each time you do something with the database? What benefits are there from using the callback style?
EDIT
I might be mistaken as to what he means by “callback style” (I’m not kidding, my JavaScript isn’t very strong) but my question is about the method of connection. I assumed the following was the callback style connection method:
// 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());
});
});
and the following is the EventEmitter API connection method:
// 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();
If I’m just getting terms mixed up here, my question still remains. pg.connect(do queries) opens a new connection every time you use it (doesn’t it?) whereas
var client = new pg.Client(conString);
client.connect();
opens a connection and then allows you to use client to run queries when necessary, no?
The EventEmitter style is more for this type of thing:
By mixing and matching, you should be able to do the following:
Note that even when using the callback style, you wouldn’t open a connect every time you want to execute a query; most likely, you’d open a connection when the application starts and use it throughout.