From what I understand after reading this question, require(ModuleName)
is a synchronous operation.
In the register-rmq.js
I have written the following:
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:
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.
Is code I have written is wrong? or Am I confused about how the operation works in this context?