Promise/async-await with mongoose, returning empty array

Viewed 2137

The console in the end returns empty array. The console runs before ids.map function finishes

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?

2 Answers

Promise.map() is now an option that would be a tiny bit more succinct option, if you don't mind using bluebird. 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. I have really enjoyed using it.

Related