Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning the result of a node-postgres query

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);
like image 773
NJerseyBoy Avatar asked Apr 23 '26 08:04

NJerseyBoy


1 Answers

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.

like image 83
Crepkey Avatar answered Apr 24 '26 23:04

Crepkey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!