简体   繁体   中英

Objects are not being pushed to array properly

I have an event listener which listens for new messages, and I want to push all new messages to an array, but when I check the result I see that only the strings are being pushed.

This is my code:

async function consume() {
  try {
    let result = [];
    const connection = await amqps.connect(URL);
    const channel = await connection.createChannel();
    await channel.consume("messages", function (message) {
      result.push(JSON.parse(message.content.toString()));
    });
    return result;
  } catch (error) {
    console.log(error);
  }
}

When I call the consume method and check the result, this is what is returned:

[
  'yoyo',   'yoyo',
  'yoyo',   'yoyo',
  'yoyo',   'yoyo',
  '',       'hi you',
  'hi you', 'hi you',
  'hi you', 'hi you',
  'hi you', 'hi you'
]

However, when I log JSON.parse(message.content.toString()) from within the listener function I can see the objects:

...
hi you
hi you
hi you
{
  read: false,
  timeSent: 1645945954348,
  message: 'Hchxh',
  userID: 41,
  contactID: 46
}
{
  read: false,
  timeSent: 1645945990969,
  message: 'Gry',
  userID: 41,
  contactID: 46
}
...

Here is the result when logging message.content.toString() (without parsing) from within the listener:

"hi you"
"hi you"
"hi you"
{"read":false,"timeSent":1645945954348,"message":"Hchxh","userID":41,"contactID":46}
{"read":false,"timeSent":1645945990969,"message":"Gry","userID":41,"contactID":46}
{"read":false,"timeSent":1645946032914,"message":"Ti","userID":41,"contactID":46}
{"read":false,"timeSent":1645946119720,"message":"Ge","userID":41,"contactID":46}
{"read":false,"timeSent":1645946454158,"message":"Beuh","userID":41,"contactID":46}
{"read":false,"timeSent":1645948170050,"message":"Xhxh","userID":41,"contactID":46}

Any ideas as to what I am doing wrong?

Try this syntax:

async function consume() {
  try {
    const connection = await amqps.connect(URL);
    const channel = await connection.createChannel();
    const result = await channel.consume('messages');
    return result.content.toString();
  } catch (error) {
    console.log(error);
  }
}

You can parse it if you want even though I'm not sure why you'd need to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM