如何使用承诺来解决这个问题?

时间:2015-11-06 12:47:18

标签: javascript node.js promise ecmascript-6

目标是让theQuery函数处理查询并将行数组返回result。在theQuery函数console.log按预期工作,但记录结果日志undefinedundefined日志首先出现在终端上。如何使用承诺来解决这个问题?

"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

1 个答案:

答案 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);
});