Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

233
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda