为了账号安全,请及时绑定邮箱和手机立即绑定

Koa2 中 export 异步返回值

Koa2 中 export 异步返回值

隔江千里 2018-10-24 21:29:35
在 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 实例对象,应该要怎么做啊?
查看完整描述

1 回答

  • 1 回答
  • 0 关注
  • 1747 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信