简体   繁体   English

Promise / async-await with mongoose,返回空数组

[英]Promise/async-await with mongoose, returning empty array

The console in the end returns empty array. 最后的控制台返回空数组。 The console runs before ids.map function finishes 控制台在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)

What am I doing wrong? 我究竟做错了什么?

The .map code isn't awaited, so the console.log happens before the mapping happens. 不等待.map代码,因此console.log在映射发生之前发生。

If you want to wait for a map - you can use Promise.all with await : 如果你想等待地图 - 你可以使用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)

Note though since you're using .map you can shorten the code significantly: 请注意,因为您使用.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); 

Promise.map() is now an option that would be a tiny bit more succinct option, if you don't mind using bluebird. Promise.map()现在是一个选项,如果你不介意使用蓝鸟,那将是一个更简洁的选项。 It could look something like: 它可能看起来像:

const user = await User.findOne(args.user);
const ids = users.following.concat(user._id);
const allLync = await Promise.map(ids, (id => Lync.find({"author": x })));
console.log(allLync); 

http://bluebirdjs.com/docs/api/promise.map.html . http://bluebirdjs.com/docs/api/promise.map.html I have really enjoyed using it. 我非常喜欢使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM