0

我已成功使用来自 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);

4

1 回答 1

2

鉴于以下情况:

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

您的期望,如下所述,

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

是一个不幸的期望。您上面的代码在每个接收到的消息的箭头函数中执行一个回调。箭头将从父上下文继承范围,但你不能去另一个方向。因此,会发生两件事:

  1. 消费被调用,并且
  2. 字符串“未定义”记录到您的控制台。那是因为要运行的下一行不在 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) { ... }
于 2019-10-02T20:10:09.160 回答