postgresqlexpressmassivejs

Error when combining Express Router with Massive.js db call


When making an async/await call to database from an express router to postgres db via massive.js instance, the correct response from db is received, but the router apparently returns before async function finishes; therefore, the test invocation returns undefined. From the console out (below), it seems clear that the async function is not waited for >_<

Is wrapping the router in order to pass the app instance causing the issue?

app.js

const app = express();
const massiveInstance = require("./db_connect");
const routes = require("./routes");

const PORT = 3001;
const server = massiveInstance.then(db => {
  // Add db into our app object
  app.set("db", db);

  app.use("/api", routes(app));

  app.listen(PORT, () => {
    console.log("Server listening on " + PORT);
  });
});

routes.js

const router = require("express").Router();
const { countRegions } = require("./db_queries");

const routes = app => {
  const db = app.get("db");

  router.get("/regions/count", async (request, response) => {
    try {
      const total = await countRegions(db);
      console.log(`There are ${total} regions.`);
      response.send(`There are ${total} regions.`);
    } catch (err) {
      console.error(err);
    }
  });

  return router;
};

module.exports = routes;

db_queries.js

const countRegions = db => {
  db.regions.count().then(total => {
    console.log(`db has ${total} count for regions`);
    return total;
  });
};

module.exports = {
  countRegions,
};

console output Server listening on 3001 There are undefined regions. db has 15 count for regions


Solution

  • You are not returning a promise returned by then in countRegions method. So you should add return in your code like this

    const countRegions = db => {
      //here
      return db.regions.count().then(total => {
        console.log(`db has ${total} count for regions`);
        return total;
      });
    };
    

    or simply do,

    return db.regions.count();