0

I used the amqplib npm package for node.js message broker stuff. I successfully created message queue, sent a message, but problem is when I try to assign it after I consume it.

I've tried creating new promise but my method is already returning a promise so no point in that. I can resolve the promise but I don't get the right result

 function Consumer() {
     return open.then(function(conn) {
         return conn.createChannel();
       }).then(function(ch) {
         return ch.assertQueue(q).then(function(ok) {
           return ch.consume(q, function(msg) {
               if (msg !== null) {
                 ch.ackAll();
                 //Here is where i get the problem
                 return msg.content.toString();
               }
           });
         });
       }).catch(console.warn);
    }

So what I get is this

{ consumerTag: 'amq.ctag-klxMp04FXQeMX4z6GJr8Yw' }

Instead of actual message which has been sent I have similar method for publishing the message and it all works fine: Message goes to queue. Even when i run this Consume method, I can log out the actual message But i cannot get it when I resolve this promise

Publisher().then(res => console.log("Publisher -> ", res));
Consumer().then(res => console.log("Consumer -> ", res));
9000
  • 39,899
  • 9
  • 66
  • 104
CyberZujo
  • 1
  • 1

1 Answers1

0
  1. If you want to chain your promise, you can't return a promise in a callback. And the ch.consume() func return void, not a promise.
  2. Callback or Observable is what you need.

Consumer can consume message multi times, but Promise can only handle single event and the success or fail callback is be called once. I think you need Observable instead of Promise. Observable allows to handle multi events and the callback is be called for each event.

By the way, the one-off promise-style consumer (NOT Recommend) looks like:

function Consumer(cb) {
  return open.then(function(conn) {
    return conn.createChannel();
  }).then(function(ch) {
    return ch.assertQueue(q);
  }).then(function() {
    return new Promise(function(resolve, reject) {
      ch.consume(q, function(msg) {
        if (msg != null) {
          ch.ack(msg);
          resolve(msg.content.toString());
        } else {
          reject('empty');
        }
      });
    })
  }).catch(console.warn);
}
menya
  • 1,459
  • 7
  • 8