0

I have started learning javascript.

I have a code from example :

Consumer = kafka.Consumer,
client = new kafka.KafkaClient();

module.exports = topic => {
  consumer = new Consumer(client, [{ topic: topic, partition: 0 }], {
    autoCommit: false
  });
  var Datas = [];
  consumer.on("message", function(message) {
    Datas.push(message);
  });

  console.log(Datas); //return = []
};

Why the message data is not pushed to array?

rdj7
  • 1,905
  • 4
  • 18
  • 33
  • move `console.log` inside `consumer.on("message", ...` and read [this](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Muhammad Usman Jan 28 '20 at 06:40

1 Answers1

0

Datas.push(message); is happening inside the listener which is asynchronous while the console statement is executed immeditaley. That is why it is empty array. You can either register end listener if there is any and do console in that or move the console inside the on message listener.

Ashish Modi
  • 7,529
  • 2
  • 20
  • 35