I wrote this code that seems to be working:
database.js
const {Pool} = require('pg');
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
});
module.exports = {
query: (text, params) => pool.query(text, params)
};
auth_facade.js
const database = require('../../utils/database');
module.exports.findPersonByEmail = async function(email) {
const query = 'SELECT * FROM Person WHERE email = $1';
const values = [email];
try {
console.log(1);
const {rows} = await database.query(query, values);
console.log(2);
return rows[0];
} catch (err) {
next(err);
}
};
auth_controller.js
const authFacade = require('./auth_facade');
module.exports.signin = async function(req, res, next) {
console.log(0);
var person = await authFacade.findPersonByEmail(req.body.email);
console.log(3);
};
It shows, as I expected, 0123.
However, I don't understand why I need the async/await on both auth_facade::findPersonByEmail and auth_controller::signin?
Why, if I remove the async from auth_controller::signin signature and the await inside it, I don't get 0123 anymore, but 0132 instead? Shouldn't it be blocked anyway be the await in auth_facade?
async/awaitin yoursigninfunction, if all it does is to callauthFacade.findPersonByEmail; otherwise, you "need" it because the underlyingpool.queryreturns a promise (so it'sasync).authFacade.findPersonByEmailisasync, so it's not blocking.