2
votes

I am attempting to return the result of a node-postgres query and store it in a variable. I can manage a console.log just fine, but cannot find a way to return the result so that it is accessible outside of the query method. I'm at a loss, and know I must be missing something obvious (or multiple obvious things), because if it isn't possible to do this I don't understand the point of node-postgres since all I will ever be able to do is log my results to the console.

I have tried the code below, along with a version using promises, and both receive the same result, 'undefined.' A console.log within the else works fine, but a return does not make the result accessible to the rest of the function. In the code below, my return comes back as 'undefined' as would a console.log in its place.

var selectFrom = function(data, table, condition) {
    var queryResult;
    pool.query(`SELECT ${data} FROM ${table} ${condition}`, function(err, result) {
        if(err) { console.log(err); }
        else { queryResult = result.rows[0][data]; }
    })
    pool.end();
    return queryResult;
}

var result = selectFrom('amount','total_nonfarm_monthly_sa', `WHERE month='2019-08-31'`);
console.log(result);
3
Your return queryResult returns before query is done. You have to somehow wait for the results to come from DB, before returning them. Read about async/await or maybe return a Promise that's resolved with result from the DB.ahwayakchih

3 Answers

4
votes

This is what you are looking for:

async function selectFrom(data, table, condition) {
  try {
    const res = await pool.query(
      `SELECT ${data} FROM ${table} ${condition}`
    );
    return res.rows[0][data];
  } catch (err) {
    return err.stack;
  }
}

Outside of the previous function:

async function whateverFuncName () {
   var result = await selectFrom('amount','total_nonfarm_monthly_sa', `WHERE month='2019-08-31'`);
   console.log(result);
}

EDIT: I didn't run this code snippet but the main concept is pretty straightforward.

1
votes

The "query" method is an async call, you should use async/await or Promise.

With async/await:

await client.connect()
const res = await client.query("SELECT amount FROM total_nonfarm_monthly_sa WHERE month='2019-08-31'");
console.log(res.rows[0]);
await client.end();

Edit: I can see that there's an option of callback, but I would use the async/await

0
votes

You need to use callbacks:

var selectFrom = function(data, table, condition, callback) {

    pool.query(`SELECT ${data} FROM ${table} ${condition}`, function(err, result) {
        if(err)
            return callback(err);
        callback(null, result.rows[0][data]);
    })
    pool.end();
}

selectFrom('amount','total_nonfarm_monthly_sa', `WHERE month='2019-08-31'`, function(err, result){
    console.log(err, result);   
});

or promises:

var selectFrom = function(data, table, condition) {
    return new Promise(function(resolve, reject){
        pool.query(`SELECT ${data} FROM ${table} ${condition}`, function(err, result) {
            if(err)
                return reject(err);
            resolve(result.rows[0][data]);
        })
        pool.end();
    });
}

selectFrom('amount','total_nonfarm_monthly_sa', `WHERE month='2019-08-31'`)
.then(function(result){
    console.log(result);    
}).catch(function(err){
    console.log(err);   
});