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
}
};