Home > Enterprise >  Nodejs: rabbitmq await consume
Nodejs: rabbitmq await consume

Time:12-06

This is my code:

// send to queue
channel.sendToQueue("test", data);

After publish test, on another server we get a response from that server

So, I want to await for it and get with await:

await channel.consume("response", async (msg) => {
  ....
})

But await not work here

How can I await for consume?

My full code:

channel.sendToQueue("test", data);
await channel.consume("response", async (msg) => {
  ....
})
// continue code

CodePudding user response:

Construct a promise and wrap it around your consume function call. It's a callback so we can just call resolve to make our outer promise actually resolve.

channel.consume doesn't return an awaitable response so we cannot await it.

await new Promise((resolve, reject) => {
  channel.consume("response", (msg) => {
    resolve(msg);
  })
}) 
  • Related