[英]Objects are not being pushed to array properly
我有一個偵聽新消息的事件偵聽器,我想將所有新消息推送到一個數組,但是當我檢查結果時,我看到只有字符串被推送。
這是我的代碼:
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);
}
}
當我調用 consume 方法並檢查結果時,這是返回的內容:
[
'yoyo', 'yoyo',
'yoyo', 'yoyo',
'yoyo', 'yoyo',
'', 'hi you',
'hi you', 'hi you',
'hi you', 'hi you',
'hi you', 'hi you'
]
但是,當我從偵聽器 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
}
...
這是從偵聽器中記錄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}
關於我做錯了什么的任何想法?
試試這個語法:
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);
}
}
如果你願意,你可以解析它,即使我不確定你為什么需要解析它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.