nodejs + pg用callback函数做crud
我正在学习nodejs
express
+ pg
。 如果我想要弄脏,我应该使用第一种方法还是第二种? 它有什么区别?
var query = "SELECT EXISTS(SELECT * FROM table WHERE user_email = '" + user_email + "')"; // 1 var result = dbClient.query(query); console.log(result); console.log(result._result.rowCount); // 2 dbClient.query(query, function(err, result) { console.log(result); console.log(result.rows[0].exists); });
连
... var conString = "postgres://db_admin:pwd@localhost/databasename"; var dbClient = new pg.Client(conString); dbClient.connect();
我会去:
// 2 dbClient.query(query, function(err, result) { if (err) { // do something with err } else{ console.log(result); console.log(result.rows[0].exists); } });
或者你可以:
如文档所示:
var query = client.query('select name from person'); var rows = []; query.on('row', function(row) { //fired once for each row returned rows.push(row); }); query.on('end', function(result) { //fired once and only once, after the last row has been returned and after all 'row' events are emitted //in this example, the 'rows' array now contains an ordered set of all the rows which we received from postgres console.log(result.rowCount + ' rows were received'); })
但是,当你深入嵌套的callback,我会build议看看使用承诺。
看到:
- 通过promises / A +使用node-postgres
- 与Bluebird手动promisifying pg.connect
- https://stackoverflow.com/a/19282657/2026508
- https://github.com/brianc/node-postgres/wiki