Node.js 异步/等待模块导出 [英] Node.js Async/Await module export

查看:26
本文介绍了Node.js 异步/等待模块导出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对模块创建有点陌生,想知道 module.exports 并等待异步函数(例如 mongo 连接函数)完成并导出结果.在模块中使用 async/await 正确定义了变量,但是当尝试通过要求模块来记录它们时,它们显示为未定义.如果有人能指出我正确的方向,那就太好了.这是我目前得到的代码:

I'm kinda new to module creation and was wondering about module.exports and waiting for async functions (like a mongo connect function for example) to complete and exporting the result. The variables get properly defined using async/await in the module, but when trying to log them by requiring the module, they show up as undefined. If someone could point me in the right direction, that'd be great. Here's the code I've got so far:

// module.js

const MongoClient = require('mongodb').MongoClient
const mongo_host = '127.0.0.1'
const mongo_db = 'test'
const mongo_port = '27017';

(async module => {

  var client, db
  var url = `mongodb://${mongo_host}:${mongo_port}/${mongo_db}`

  try {
    // Use connect method to connect to the Server
    client = await MongoClient.connect(url, {
      useNewUrlParser: true
    })

    db = client.db(mongo_db)
  } catch (err) {
    console.error(err)
  } finally {
    // Exporting mongo just to test things
    console.log(client) // Just to test things I tried logging the client here and it works. It doesn't show 'undefined' like test.js does when trying to console.log it from there
    module.exports = {
      client,
      db
    }
  }
})(module)

这是需要模块的js

// test.js

const {client} = require('./module')

console.log(client) // Logs 'undefined'

我对 js 相当熟悉,并且仍在积极学习和研究诸如 async/await 和类似功能之类的东西,但是是的...我真的想不通

I'm fairly familiar with js and am still actively learning and looking into things like async/await and like features, but yeah... I can't really figure that one out

推荐答案

必须同步导出,无法直接导出clientdb.但是,您可以导出解析为 clientdb 的 Promise:

You have to export synchronously, so its impossible to export client and db directly. However you could export a Promise that resolves to client and db:

module.exports = (async function() {
 const client = await MongoClient.connect(url, {
   useNewUrlParser: true
 });

  const db = client.db(mongo_db);
  return { client, db };
})();

那么你可以将其导入为:

So then you can import it as:

const {client, db} = await require("yourmodule");

(必须在异步函数中)

PS:console.error(err) 不是一个合适的错误处理程序,如果你不能处理错误就崩溃

PS: console.error(err) is not a proper error handler, if you cant handle the error just crash

这篇关于Node.js 异步/等待模块导出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆