javascript – 使用mongoose进行Promise / async-await,返回空数组

最后的控制台返回空数组.
控制台在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在映射发生之前发生.

如果你想等待地图 – 你可以使用Promise.all等待:

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); 

相关文章

最后的控制台返回空数组.控制台在ids.map函数完成之前运行va...
我正在尝试将rxJava与我已经知道的内容联系起来,特别是来自J...
config.jsconstconfig={base_url_api:"https://douban....
我正在阅读MDN中的javascript,并且遇到了这个谈论承诺并且不...
config.jsconstconfig={base_url_api:"https://douban....
这是我的代码main.cpp:#include<string>#include<...