Search code examples
javascriptnode.jsasync-awaites6-promisenode-postgres

Why do I need to use async/await twice in node-postgres


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?


Solution

  • Your current code:

    A family goes to a mall. (0) Dad is tired and says "Go ahead do some shopping, I'll wait then we'll all go home together." (1) A little later daughter says "I don't feel like going into that shop, I'll just hang out here, waiting for you, and then we'll go back to Dad." (2) Mom finishes shopping and returns to daughter, (3) they both come back to pick up Dad and all go home together.

    Your code without the outer await:

    A family goes to a mall. (0) Dad is tired and says "Go ahead do some shopping, I'll be here." (1) A little later daughter says "I don't feel like going into that shop, I'll just hang out here, waiting for you, and then we'll go back to Dad." However, at about the same time, (3) Dad turns around and decides to go home, because waiting is for losers. (2) Mom finishes shopping and returns to daughter, they both come back to find Dad is gone with the car and they're stuck in the mall with a bunch of shopping bags.

    Both daughter and Dad need to wait in order for them not to leave someone behind.