我正在尝试使用 amqp 库构建一个简单的 node.js 客户端,它打开一个连接,然后打开一个到 RabbitMQ 服务器的通道。我想重用相同的连接和通道来发送多条消息。主要问题是,我不想在 ceateChannel() 函数的回调函数中编写我的整个代码。
如何在回调函数之外重用通道并确保在使用通道之前回调函数已完成?
我已经尝试了回调方式和承诺方式,但我无法让它们中的任何一个工作。使用回调方法时,我遇到了所描述的问题。
使用 promise 时,我遇到的问题是我无法在 .then() 函数之外保留连接和通道的引用,因为在设置连接和通道后传递的变量会被破坏。
amqp.connect('amqp://localhost', (err, conn) => {
if (err !== null) return console.warn(err);
console.log('Created connection!');
conn.createChannel((err, ch) => {
if (err !== null) return console.warn(err);
console.log('Created channel!');
//this is where I would need to write the code that uses the variable "ch"
//but I want to move the code outside of this structure, while making sure
//this callback completes before I try using "ch"
});
}); …Run Code Online (Sandbox Code Playgroud)