Koa2 中 export 异步返回值

在 koa2 中抽象一个 Mongodb 实例模块。

// mongoUtil.jsconst MongoClient = require('mongodb').MongoClient;async function getMongoDB() {  try {    const client = await new MongoClient('mongodb://localhost:27017/test').connect();
    db = client.db();    return db;
  } catch (err) {
    client.close();
  }
}module.exports = getMongoDB;

在其他中间件中使用此模块

const router = require('koa-router')();let mongo = require('../db/mongoUtil')();

router.get('/test', async (ctx, next) => {
  ctx.body = {"Koa": "Hello World"};  const db = await mongo;  const col = db.collection('log');  const cursor = col.find({});  while(await cursor.hasNext()) {    const doc = await cursor.next();    console.dir(doc);
  }
});module.exports = router;

我知道在 require 返回一个的是 promise 对象,所以我使用时 const db = await mongo;

我现在想 mongoUtil.js 文件中直接返回 mongodb 实例对象,应该要怎么做啊?


隔江千里
浏览 1749回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP