最后控制台返回空数组。 控制台在 ids.map 函数完成之前运行
var ids = [];
var allLync = []
var user = await User.findOne(args.user)
ids.push(user._id)
user.following.map(x => {
ids.push(x)
})
ids.map(async x => {
var lync = await Lync.find({ "author": x })
lync.map(u => {
allLync.push[u]
})
})
console.log(allLync)
我做错了什么?
最佳答案
没有等待 .map
代码,因此 console.log
在映射发生之前发生。
如果你想等待 map - 你可以使用 Promise.all
和 await
:
var ids = [];
var allLync = []
var user = await User.findOne(args.user)
ids.push(user._id)
user.following.map(x => {
ids.push(x)
})
// note the await
await Promise.all(ids.map(async x => {
var lync = await Lync.find({ "author": x })
lync.map(u => {
allLync.push(u); // you had a typo there
})
}));
console.log(allLync)
请注意,由于您使用的是 .map
,因此您可以显着缩短代码:
const user = await User.findOne(args.user)
const ids = users.following.concat(user._id);
const allLync = await Promise.all(ids.map(id => Lync.find({"author": x })));
console.log(allLync);
关于javascript - 使用 Mongoose promise /异步等待,返回空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44094358/