目标是让theQuery
函数处理查询并将行数组返回result
。在theQuery
函数console.log
按预期工作,但记录结果日志undefined
。 undefined
日志首先出现在终端上。如何使用承诺来解决这个问题?
"use strict";
var pg = require('pg').native;
var connectionString = "...";
var client = new pg.Client(connectionString);
client.connect();
function theQuery(table,column) {
client.query('SELECT * FROM "'+table+'" WHERE column = '+"'"+column+"';", function(err, result) {
if(err) {
return console.error('error running query', err);
}
console.log(result.rows);//works logs the rows
return result.rows;
});
}
let Query = theQuery("table", "column);
console.log(result);// logs undefined
答案 0 :(得分:1)
这应该有效:
"use strict";
var pg = require('pg').native;
var connectionString = "...";
var client = new pg.Client(connectionString);
client.connect();
function theQuery(table,column) {
return new Promise(function(fulfill, reject){
client.query('SELECT * FROM "'+table+'" WHERE column = '+"'"+column+"';", function(err, result) {
if(err) {
reject(console.error('error running query', err));
}
console.log(result.rows);//works logs the rows
fulfill(result.rows);
});
});
}
theQuery("table", "column).then(function(result){
console.log(result);
});