【发布时间】:2015-09-23 01:07:26
【问题描述】:
谁能给我看一个将 Nodejs 中的 postgres 查询结果传递给另一个函数的示例?
【问题讨论】:
-
我确定google 可以。
-
用pg-promise将结果作为promise请求,然后将返回的promise传递给你的函数。
标签: javascript node.js postgresql
谁能给我看一个将 Nodejs 中的 postgres 查询结果传递给另一个函数的示例?
【问题讨论】:
标签: javascript node.js postgresql
我有一个config.json 文件,用于存储我的配置。
var pg = require('pg')
,q = require('q')
,config = require('custom-modules/config.json')
conString = 'postgres://'+ config.pg.admun +':' + config.pg.admpw + '@' + config.pg.host + ':' + config.pg.port + '/' + config.pg.defdb;
function runSQL (sqlStatement) {
var deferred = q.defer();
var results = [];
// Get a Postgres client from the connection pool
pg.connect(conString, function(err, client, done) {
// SQL Query > Select Data
var query = client.query(sqlStatement, function(err, res) {
if(err) console.log(err);
deferred.resolve(res);
});
// After all data is returned, close connection and return results
query.on('end', function() {
client.end();
deferred.resolve(results);
});
// Handle Errors
if(err) {
console.log(err);
}
});
return deferred.promise;
};
现在你可以像这样运行函数了:
runSQL("SELECT * FROM tablename").then(function(res) {
// here you have access to the result of the query... with "res".
console.log(res);
});
【讨论】: