Hi I have a very important question that im not understanding.
I have 2 codes with a free variable called 'instance'. in the first the variable stay with his value whenever im require the file in the app(Promise/Object value), the second is mentioned as undefined every time like i didnt initialize him.
now i know that the first one is a singleton but i don't understand why in one case he can hold the data and in the other case he is not and getting undefined every time.
let instance;
class MessageBroker {
async init() {
this.connection = await amqp.connect(process.env.MQ_URL)
this.channel = await this.connection.createChannel()
return this
}
async pushToRabbitQueue(queueName, data) {
if (!this.connection) {
await this.init();
}
await this.channel.assertQueue(queueName, {durable: true});
return this.channel.sendToQueue(queueName, Buffer.from(data));
}
async listenToRabbitQueue(queueName, callback) {
if (!this.connection) {
await this.init();
}
await this.channel.assertQueue(queueName, { durable: true });
this.channel.consume(queueName, callback, { noAck: true });
}
}
MessageBroker.getInstance = async function() {
if (!instance) {
const broker = new MessageBroker()
instance = broker.init()
}
return instance
};
module.exports = MessageBroker
const connectToRMQChannel = async () => {
const connection = await amqp.connect(process.env.MQ_URL);
return await connection.createChannel();
}
let instance;
const pushToRabbitQueue = async (data, queueName = process.env.RABBITMQ_LEVEL2_LOGS_QUEUE_NAME) => {
if (!instance) {
instance= await connectToRMQChannel();
}
return await instance.sendToQueue(queueName, Buffer.from(data));
}
module.exports = {
pushToRabbitQueue
}
thanks, I really like to understand it.