[英]NodeJS - requiring module is not working synchronously
From what I understand after reading this question, require(ModuleName)
is a synchronous operation.根据我阅读这个问题后的理解, require(ModuleName)
是一个同步操作。
In the register-rmq.js
I have written the following:在register-rmq.js
我写了以下内容:
const amqp = require('amqplib/callback_api');
function main(){
return new Promise(function(resolve,reject){
amqp.connect('localhost:5672', function(error0, connection) {
if (error0) {
throw error0;
}
connection.createChannel(function(error1, channel) {
if (error1) {
reject(error1);
}
channel.assertQueue('', {
exclusive: true
}, function(error2, q) {
if (error2) {
reject(error2);
}
});
resolve(channel); //
});
});
})
}
main().then(function(result){
module.exports = {result}
})
In my controller.js
I have the following two lines of code:在我的controller.js
我有以下两行代码:
var channel = require('./register-rmq');
console.log(channel);
What I am expecting from the code is that the line after requiring the module in contoller.js
gives me the object that I am expecting from the module which I am requiring, however the console.log
that I have in controller.js
gets executed before the promise
gets return and therefore the channel
object is empty in the controller.我对代码的期望是,在需要contoller.js
的模块之后的行给了我我期望从我需要的模块中获得的对象,但是我在controller.js
的console.log
在之前被执行promise
得到回报,因此channel
对象在控制器中是空的。
Is code I have written is wrong?我写的代码是错误的吗? or Am I confused about how the operation works in this context?或者我是否对操作在这种情况下的工作方式感到困惑?
You've already highlighted that exporting a module is done synchronously;您已经强调导出模块是同步完成的; you can't wait until a promise is resolved (or, any asyncronous operation) and expect the correct value to be exported synchronously.您不能等到承诺得到解决(或任何异步操作)并期望同步导出正确的值。
The most appropriate pattern in this scenario would be the following.这种情况下最合适的模式如下。
register-rmq.js注册-rmq.js
module.exports = main();
controller.js控制器.js
var channel = require('./register-rmq');
channel.then(result => console.log(result));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.