亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 1882 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號