此代码搜索一家公司,然后搜索该公司数组中列出的所有网站,然后搜索该网站上的所有对话,然后搜索每个对话的所有消息,然后发送这些消息数组helper
函数的 ObjectID,然后该函数返回每条消息的 JSON 数据数组。呃..那是一口。
我需要以某种方式等待所有这些完成,然后再稍微清理一下,然后重新发送它。所有代码都有效,并且 console.log(messagesWithData)
发布了一些消息数组(因为在这种情况下发送了一些消息)。
感谢所有帮助:)
Company.findOne({ 'roles.admins': userId }, function (err, doc) {
if (!err) {
for (const item of doc.websites) {
Website.findById(item, function (err, doc) {
for (const item of doc.conversations) {
Conversation.findById(item, function (err, doc) {
async function findMessageData() {
var messagesWithData = await helper.takeMessageArray(
doc.messages
);
await sendMessages(messagesWithData);
}
findMessageData();
async function sendMessages(messagesWithData) {
// not sure what to put here!
console.log(messagesWithData)
}
});
}
});
}
} else {
res.send(err);
}
});
最佳答案
上面的代码可以使用 async/await 稍微简化
const company = await Company.findOne({ 'roles.admins': userId });
let allMessages = []
for (const websiteId of company.websites) {
const website = await Website.findById(websiteId);
for (const conversationId of website.conversations) {
const conversation = await Conversation.findById(conversationId);
const messagesWithData = await helper.takeMessageArray(
conversation.messages
);
allMessages = [...allMessages, ...messagesWithData]
}
}
// Everything completed, messages stored in one place...
console.log(allMessages)
关于javascript - 异步代码和 mongodb 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61196032/