将Express Router与Massive.js db调用结合使用时出错

时间:2018-10-01 03:28:15

标签: postgresql express massivejs

当从Express路由器通过massive.js实例对Postgres db进行数据库异步/等待调用时,收到了来自db的正确响应,但是路由器显然在异步功能完成之前返回了;因此,测试调用返回未定义。从控制台出来(如下所示),很明显,异步功能没有等待> _ << / p>

包装路由器是为了传递导致问题的应用实例吗?

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

控制台输出 Server listening on 3001 There are undefined regions. db has 15 count for regions

1 个答案:

答案 0 :(得分:1)

您没有在then方法中返回countRegions返回的承诺。 因此,您应该像这样在代码中添加return

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

或者干脆做

return db.regions.count();