以不寻常的方式使用 module.exports [英] using module.exports in an unusual way

查看:36
本文介绍了以不寻常的方式使用 module.exports的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我也想在其他模块中使用 mongodb 连接,所以我选择了这种方法.是否有任何缺点或我应该注意的事情.我将在我的 app.js 文件中要求这个文件.或者有没有其他优雅的方式来做同样的事情.

I want to use the mongodb connection in other modules also so I chose this approach. Is there any drawback or something that I should be aware of. I am going to require this file in my app.js file. or Is there any other elegant way of doing the same thing .

const uri = "mongodb://localhost";
const MongoClient = require('mongodb').MongoClient;
const client = new MongoClient(uri, { useNewUrlParser: true });

db = null ;
client.connect().then(()=>{
    db = client.db("mydb");
    db.collection("users").createIndex({ mobno: 1 }, { sparse: true, unique: true });
}).catch((error)=>{
    db = error;
});
while(true){
    if (db!=null){
        module.exports = db;
        break;
    }
}

推荐答案

这有很多问题.这个概念行不通.

Lots of things wrong with this. This concept won't work.

对于初学者来说,您的 while(true) 循环会阻塞事件循环,因此 db 永远无法获得值,因此您的循环永远不会完成.

For starters, your while(true) loop blocks the event loop so db can never get a value so your loop never completes.

当connect中的网络操作完成时,它会向事件队列中添加一个事件,并且与之关联的回调(然后是已解析的promise)只有在您将控制权返回给事件循环时才能运行,以便事件可以得到处理.

When the network operation in the connect completes, it will add an event to the event queue and the callback associated with it (and then the resolved promise) can only run when you return control back to the event loop so that event can get processed.

但是,您的 while(true) 循环会阻塞事件循环,因此无法处理任何事件.除非您在循环内使用 await (允许其他事件运行),否则您不能在 node.js 中使用这样的等待循环.它只会创建一个无限循环.

But, your while(true) loop blocks the event loop so no events can get processed. Unless you're using await inside the loop (which allows other events to run), you can't use a wait loop like this in node.js. It just creates an infinite loop.

在我们拥有与模块初始化(正在处理)一起工作的顶级 await 之前,您不能直接导出异步获取的值.

Until we have top level await that works with module initialization (which is being worked on), you cannot directly export a value obtained asynchronously.

相反,您可以导出一个承诺,而调用者必须使用该承诺来获取数据库.或者导出一个返回承诺的函数.

Instead, you can export a promise and the caller has to use the promise to get the db. Or export a function that returns a promise.

在这些其他答案中有关忙等待 while 循环问题的更多信息:

More info on problems with the busy-wait while loop in these other answers:

等到 flag=true

javascript - 什么这个while循环有问题吗?永无止境的循环

为什么while循环会阻塞事件循环?

这篇关于以不寻常的方式使用 module.exports的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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