简体   繁体   中英

How to return data from RabbitMQ consume function in nodejs?

I have consume function like this.

In this case when i put console.log() in consume callback function, i see messages coming from queue.

Function 1

 async function consumeData() {
  try {
    const connection = await amqp.connect("amqp://localhost:5672");
    const channel = await connection.createChannel();
    await channel.assertQueue(queueName);
    let consumedData;

    channel.consume(queueName, (message) => {
      consumedData = message.content.toString();
      console.log(consumedData);
      channel.ack(message);
    });
  } catch (error) {
    console.log("Error", error);
  }
}

But i dont wanna log this data. I wanna return and use it like this.

Function 2

 async function consumeData() {
  try {
    const connection = await amqp.connect("amqp://localhost:5672");
    const channel = await connection.createChannel();
    await channel.assertQueue(queueName);
    let consumedData;

    channel.consume(queueName, (message) => {
      consumedData = message.content.toString();
      console.log(consumedData);
      channel.ack(message);
    });
    
    return consumedData;
  } catch (error) {
    console.log("Error", error);
  }
}

When i run function 2 i cant return any data. How can i return data from this consume function?

return it after trycatch

 async function consumeData() {
  var consumedData = {};
  try {
    const connection = await amqp.connect("amqp://localhost:5672");
    const channel = await connection.createChannel();
    await channel.assertQueue(queueName);
    let consumedData;

    channel.consume(queueName, (message) => {
      consumedData = JSON.parse(message.content.toString());
      channel.ack(message);
    });
  } catch (error) {
    console.log("Error", error);
  }
  return consumedData;
}

and call the function using await

const data = await consumeData();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM