Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promise/async-await with mongoose, returning empty array

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?

like image 499
ANKIT HALDAR Avatar asked Nov 27 '25 03:11

ANKIT HALDAR


1 Answers

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

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); 
like image 58
Benjamin Gruenbaum Avatar answered Nov 28 '25 15:11

Benjamin Gruenbaum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!