Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

227
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda