我使用nodejs amqplib 模块连接rabbitmq。我发现consume函数变成了一个闭包函数,但我不明白为什么。我没有使用闭包。
我的代码如下。我发现returnOK中的corr仍然获得了第一次值。当我第二次触发此功能时。corr 仍然是第一次的值。我认为这很奇怪。有人可以解释一下吗?
const corr = new Date().getTime();
try {
const params = JSON.stringify(req.body);
console.log('corr first =', corr);
await ch.sendToQueue(q, Buffer.from(params), {
deliveryMode: true,
correlationId: corr.toString(),
replyTo: queue.queue,
});
const returnOK = (msg) => {
if (msg.properties.correlationId === corr.toString()) {
console.info('******* Proxy send message done *******');
res.status(HTTPStatus.OK).json('Done');
}
};
await ch.consume(queue.queue, returnOK, { noAck: true });
} catch (error) {
res.status(HTTPStatus.INTERNAL_SERVER_ERROR).json(error);
}