0

If I use the following code NATS listens and processes the first message but not new messages after that. How do I make the sub not close and continuously process messages?

The code below is from the NATS sample code I'm testing with. In can be found here in the fist example under "Publish and Subscribe".

What happens is if I add an async fn just before the console.log to process the message then the for loop exists and does not process any more messages. If I don't to this, it continuously processes new messages and the console.log never prints. How can I make a call inside the loop and not exist?

(async () => {
  for await (const m of sub) {
    console.log(`[${sub.getProcessed()}]: ${sc.decode(m.data)}`);
  }
  console.log("subscription closed");
})();
Jason Leach
  • 3,889
  • 7
  • 37
  • 54
  • Please show more relevant code that shows what module you are importing, shows what `sub` is. Shows any relevant initialization code. So far, you seem to be assuming we know more than we do about what this is doing or is supposed to do. – jfriend00 Jul 08 '23 at 17:02
  • Perhaps relevant: https://stackoverflow.com/questions/63647226/how-to-loop-nats-messages-received-over-channel?rq=2 – jfriend00 Jul 08 '23 at 17:03
  • @jfriend00 I'm just looking at the example code for the module and testing it. It can be found [here](https://www.npmjs.com/package/nats/v/2.15.1), the fist example under "Publish and Subscribe". I'm thinking some sort of `while (true)` but that seems old-skool. Event handling seems better. – Jason Leach Jul 08 '23 at 19:07
  • 1
    Please edit your question to add that info to your question. – jfriend00 Jul 08 '23 at 21:52

1 Answers1

0

Since you didn't provide the entire code (connection, subscription, etc), what I can imagine is that you are not passing the subscription as a parameter to your anonymous function.

Look at this working example:

async function connectAndListen() {
        const nc = await connect({ servers: 'nats://localhost:4222' });
        const sc = StringCodec();
        const subscription = nc.subscribe('subject');

        (async (sub) => {

            console.log(`listening for ${sub.getSubject()} requests...`);

            for await (const m of sub) {
                console.log(sc.decode(m.data))
            }
            
            console.log(`subscription ${sub.getSubject()} drained.`);
        })(subscription);
}

connectAndListen();

On the example, the anonymous function receives sub parameter (the subscription), and at the end of the function declaration, we are calling itself passing subscription as the sub parameter.

Bipe
  • 27
  • 5