0

I have this line of codes:

let message = channel.consume(queue, msg => {
  console.log('Return this in the "message" variable', msg.content); 
});

When I tried to log the value of message, it does not equate to msg.content but it gets the value from the return of consume method. What's the workaround in order for me to get the right value from the callback.

Thanks

Brad
  • 159,648
  • 54
  • 349
  • 530
jhnferraris
  • 1,361
  • 1
  • 12
  • 34
  • I don't follow at all what you're asking. I don't know what `channel.consume()` returns and sends to the callback so you'll have to first explain that. Then, explain what exactly you are expecting to happen. – Brad Sep 15 '16 at 04:14
  • Someone needs to write a new general purpose answer for asynchronous functions that includes coroutines, async/await and promises. – slebetman Sep 15 '16 at 04:23

2 Answers2

1
var message;
channel.consume(queue, msg => { message = msg.content; });

Not really sure what you're asking, but are you trying to set message within the callback? If so, see above.

vol7ron
  • 40,809
  • 21
  • 119
  • 172
  • Nice! I forgot to try that out. Thank you! – jhnferraris Sep 15 '16 at 05:02
  • Just be sure you realize that this is not guaranteed to be synchronous. I don't know what *consume* is, but even though code *message* may appear to be loaded after, unless *consume* is a blocking function, there's a possibility other code will execute before *message* populates. – vol7ron Sep 15 '16 at 05:09
0

You cannot "return" the value of the callback. Also, there's little point in doing so since the line after that code will execute before the callback has even executed.

While it's not "returning" the value, you can use a Promise.

If you can transpile from ES7, you can use async-await which allows you to call asynchronous functions using synchronous-looking code within an async function using await.

Joseph
  • 117,725
  • 30
  • 181
  • 234