我正在端点上调用以下方法
exports.allConversations = async (req, res) => {
// The recipient of the call, a phone number or a client
console.log(req.body);
let phoneNumber = req.body.phoneNumber;
let messageSent, messageReceived;
try {
let messageSentPromise = client.messages
.list({
from: phoneNumber,
limit: 20
});
let messageReceivedPromise = client.messages
.list({
to: phoneNumber,
limit: 20
});
[messageSent, messageReceived] = await Promise.all([messageSentPromise, messageReceivedPromise]);
let conversations = [];
for (let i = 0; i < messageSent.length; i++) {
let message = messageSent[i];
if (conversations.includes(message.to))
conversations[message.to].push(message);
else {
console.log([].push(message));
conversations[message.to] = [message];
}
}
console.log(conversations);
return res.status(200).send({
conversations: conversations
});
}
catch (error) {
console.log(error);
return res.status(200).json({
success: false
});
}
}
console.log(对话); 在响应中,我总是收到一个空数组,但在以下代码上方的console.log
return res.status(200).send({
conversations: conversations
});
在控制台上打印阵列。
答案 0 :(得分:1)
我认为问题可能是由于数组索引不是实际的正整数。可能导致异常行为,如以下代码段所示:
let result = [];
result["test"]="test";
console.log(result); // depending on the implementation can still log `[test: "test"]` works in newest version of nodejs and firefox for instance
console.log(JSON.stringify(result)); // will always log `[]`
就像使用浮点数一样,问题可能不那么明显,只需确保索引实际上是有效的数组索引或使用对象即可,如下面的代码所示
let conversations = {};
for (let i = 0; i < messageSent.length; i++) {
let message = messageSent[i];
if (conversations[message.to]) conversations[message.to].push(message);
else conversations[message.to] = [message];
}
console.log(conversations);
return res.status(200).json({conversations});