Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

224
Views
Javascript cached variables

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.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!