0

New student here. I'm trying to learn and understand how to query a postgresql database and await the results. I wrote a simple test helper function, using node and pg, trying to return the results of a query. How do I go about and await the results of the query and then return the results?

const selectEnvelope = (name) => {
    var envelope = [];
    pool.query('SELECT * FROM envelopes WHERE name = $1', [name])
        .then(results => {
            envelope = results.rows;
        })
    return envelope;
};

I think I understand "return envelope" will run before the promise finishes, however I left it there as I think it better shows what I'm trying to accomplish.

I initially tried placing the return inside the .then and get undefined. Gave it another try with the following code, but only get a promise pending even though it logs correctly.

async function selectEnvelope(name) {
    try {
        var envelopes = await pool.query('SELECT * FROM envelopes WHERE name = $1', [name])
        console.log(envelopes);
        return envelopes;
    } catch (err) {
        throw err
    }
};
masutuda
  • 1
  • 1
  • 1
    tl;dr: A value cannot time travel into the past. Any value obtained by an asynchronous call needs to be handled _then_, not now. There is no way to pull a value from _then_ to now. Reorganise your thinking, so that you either propagate the asynchronicity by returning the promise, or you use the value inside your asynchronous function, or you take a callback argument that specifies what will happen to the value once it is received. – Amadan Aug 14 '22 at 16:19
  • First off, thanks Amadan for your help. I will continue to study the link you provided. I added some other methods I tried, but still get stuck with a promise pending. Trying to understand why it logs correctly before the return – masutuda Aug 14 '22 at 17:18
  • "*Gave it another try with the following code, but only get a promise pending even though it logs correctly.*" - that's the expected behaviour, and you won't get around that. In the code calling this function, you can just `await` it again – Bergi Aug 14 '22 at 22:41

0 Answers0