使用node-postgres从SELECT返回结果

mag*_*dae 11 postgresql rest node.js

无法从node-postgres中的SELECT查询中获取结果.现在,代码块末尾的行为空.此选择只返回POSTGRESQL中序列的下一个值.我知道你无法从回调中检索结果,但是这里是否有人使用过node-postgres(或任何其他数据库模块到节点)可能知道修复?

client.connect();
var query = client.query("SELECT nextval(\'idgenerator\');");
var rows = [];
query.on('row', function(row, res) {
    rows.push(row);
});
query.on('end', function(result) {
    console.log(result.rowCount + ' rows were received');
});
//client.end();
console.log(rows);
Run Code Online (Sandbox Code Playgroud)

Dra*_*ill 7

你必须学习javascript/nodejs和事件编程.

query.on('row', function() { /*CODE*/ }) 意思是:"当读取一行时,执行CODE".

这是异步的; 所以query.on()注册事件,然后返回.

So when console.log(rows) 在调用时,行仍为空,因为在查询时尚未触发"行"事件.

您应该尝试在query.on('end')事件处理程序的主体中放入'console.log(rows)'.

在代码中的任何地方,你也应该写一些console.log.你会看到异步的东西.