如何确保来自导入模块的异步代码在当前模块的代码开始之前完成?

问题描述

我想先通过模块 A 中的 mongoose.connect() 连接到 MongoDB,然后使用此连接在模块 B 中发送请求。

问题是 mongoose.connect()一个异步函数,所以模块 B 中的请求在模块 A 的连接完全建立之前发送,导致它们超时。

如何解决上述问题?

最小可重复示例:

app.js(又名“模块 A”,建立连接的地方)

const mongoose = require('mongoose')


const mongoURL = //replace this with your own Mongo URL

const connectAndReturnApp = async () => {
  try {
    await mongoose.connect(mongoURL,{
      useUnifiedTopology: true,useNewUrlParser: true,useCreateIndex: true,useFindAndModify: false
    })
  } catch (err) {
    console.log(err)
  }
  const app = 'thisIsJustAPlaceHolderForExport'
  return app
}

module.exports = connectAndReturnApp()

index.js(又名“模块 B”,其中模块 A 的连接用于向 MongoDB 发送请求)

const mongoose = require('mongoose')
const app = require('./app')


const exampleSchema = new mongoose.Schema({
  title: String,author: String
})
const Example = mongoose.model('Example',exampleSchema)

const exampleOne = new Example({
  title: 'Don Quixote',author: 'M. Cervantes'
})

const main = async () => {  
  try {
    const res = await exampleOne.save()  
    console.log(res)
  } catch (err) {
    console.log(err)
  }
  mongoose.connection.close()
}

main() //This leads to timeout when called =,(

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)