如何从channel.consume

时间:2019-10-02 03:19:06

标签: node.js rabbitmq node-amqplib

我已成功使用了Rabbitmq的消息,如果添加了console.log(msg),则可以看到消息,但是问题是我无法在channel.consume之外获取消息

我试图将其分配给变量,但仍然无法正常工作

const connection = await amqp.connect("amqp://localhost")
const channel = await connection.createChannel()
const queue = 'data-portal-response'

var messageString;
channel.consume(queue, msg => {
    console.log('Checking message...');
    if (msg !== null) {
        messageString = msg.content.toString();
        console.log('Acknowledging message..');
        channel.ack(msg);
        console.log('Acknowledged.');
        return messageString;
    } else {
        console.log('No messages to consume.');
        return null;
    }
});


console.log(messageString);

我期望代码在消耗部分之外打印messageString console.log(messageString);

1 个答案:

答案 0 :(得分:2)

给出以下内容:

channel.consume(queue, msg => { ... });

您的期望,如下所述,

  

我希望代码在消费部分console.log(messageString);之外打印出messageString

是不幸的期望。上面的代码对每个收到的消息在arrow函数中执行回调。箭头将继承父上下文的作用域,但是您不能向其他方向移动。因此,发生了两件事:

  1. 调用消费,并且
  2. 字符串“ undefined”已记录到控制台。这是因为下一条要运行的行不在lambda内,而是console.log(messageString),当时未定义。

相反,您需要在箭头功能内移动console.log语句。如果您需要在父范围内运行其他功能(我假设这是您所需要的),则必须将其定义为单独的功能,然后从箭头功能中调用它。

例如:

let consumerTag = channel.consume(queue, msg => {
    console.log('Message received: ...');
    var messageString = msg.content.toString();
    this.doSomethingUsefulWith(messageString);

    console.log('Acknowledging message..');
    channel.ack(msg);
});

function doSomethingUsefulWith(messageString) { ... }