[英]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:当我调用 consume 方法并检查结果时,这是返回的内容:
[
'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:但是,当我从侦听器 function 中记录
JSON.parse(message.content.toString())
时,我可以看到对象:
...
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:这是从侦听器中记录
message.content.toString()
(不解析)时的结果:
"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.如果你愿意,你可以解析它,即使我不确定你为什么需要解析它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.