Promise/async-await with mongoose, returning empty array Promise/async-await with mongoose, returning empty array mongoose mongoose

Promise/async-await with mongoose, returning empty array


The .map code isn't awaited, so the console.log happens before the mapping happens.

If you want to wait for a map - you can use Promise.all with 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 awaitawait 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:

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. 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.