【发布时间】:2019-03-31 22:10:02
【问题描述】:
我在操作全局数组时遇到问题。
如果这样写,代码运行良好
function getChatBox(originMessage) {
return new Promise((resolve, reject) => {
resolve(
Message.aggregate([
{
$match: { _id: originMessage }
},
{
$unwind: "$subMessages"
},
{
$lookup: {
from: "messages",
localField: "subMessages",
foreignField: "_id",
as: "chained"
}
},
{
$unwind: "$chained"
},
{
$project: { chained: 1, _id: 0 }
}
])
);
});
}
let chatBoxes = [];
if (user.messages.length > 0) {
user.messages.forEach(async msg => {
//let chatBox = await getChatBox(msg.originMessage);
//chatBoxes.push(chatBox);
//chatBoxes.push(await getChatBox(msg.originMessage));
chatBoxes.push("cool");
console.log(chatBoxes);
});
}
console.log("outer", chatBoxes);
And the output is like this when it works
但是,一旦我添加了一行代码(用于从数据库中获取数据),全局数组就不会改变。
在** **之间是添加的代码行(let chatBox = await getChatBox(msg.originMessage);):
function getChatBox(originMessage) {
return new Promise((resolve, reject) => {
resolve(
Message.aggregate([
{
$match: { _id: originMessage }
},
{
$unwind: "$subMessages"
},
{
$lookup: {
from: "messages",
localField: "subMessages",
foreignField: "_id",
as: "chained"
}
},
{
$unwind: "$chained"
},
{
$project: { chained: 1, _id: 0 }
}
])
);
});
}
let chatBoxes = [];
if (user.messages.length > 0) {
user.messages.forEach(async msg => {
**let chatBox = await getChatBox(msg.originMessage);**
//chatBoxes.push(chatBox);
//chatBoxes.push(await getChatBox(msg.originMessage));
chatBoxes.push("cool");
console.log(chatBoxes);
});
}
console.log("outer", chatBoxes);
输出显示如下: I don't know why the order of the logs changing
请帮助我了解发生了什么。 我想将获取的数据推入全局数组(chatBoxes),但在函数之外,数组仍然是空的(如果我在函数中添加一个简单的字符串,则不是空的)。
我怀疑 forEach 之后的代码在结束循环之前运行。也许这就是问题所在?
谢谢!
【问题讨论】:
-
如果可以,请将您的实际代码作为文本编辑到您的问题中 - 代码单独的图像是tedious and difficult,可以使用和调试.它会迫使那些本来愿意帮助你的人先transcribe your image,这是浪费时间。
标签: javascript node.js mongodb scope global-variables