0

The goal is to have theQuery function handle the query and return an array of the rows back to result. In the theQuery function console.log works as expected, but logging result logs undefined. The undefined log occurs first on the the terminal. How can a promise be used to fix this?

"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
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 1
    You are trying to return a value from a callback function. This indicates a profound misunderstanding about asynchronous code. Refer to the duplicate thread. – Tomalak Nov 06 '15 at 12:51
  • @Tomalak I tried the solutions at https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call but I could not get them working that is why I am specifically asking about promises and how to implement them in this case. –  Nov 06 '15 at 12:59
  • 1
    "I could not get them working" is by far not enough to go on. The other thread goes into specific detail about how asynchronous programming works, there is no way you have tried everything in there in such a short time. – Tomalak Nov 06 '15 at 13:04
  • 1
    How to use promises is exactly explained in the linked question. There are also links for further information. See the "Use promises" section. The example couldn't be any simpler. – Felix Kling Nov 06 '15 at 15:03
  • [pg-promise](https://github.com/vitaly-t/pg-promise) already does everything you need here. – vitaly-t Nov 06 '15 at 18:06

1 Answers1

1

This should work:

"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);
});
Domysee
  • 12,718
  • 10
  • 53
  • 84