3

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?

3
  • what is the value of lync - try adding console.log(lync) to see what Lync.find({ "author": x }) is returning to you - by the way, that is a really bad use of .map - the way you wrote that, you may as well use .forEach Commented May 21, 2017 at 7:44
  • @JaromandaX you're right but a small nit: OP actually does need .map here since they need the promises back to await them before the log Commented May 21, 2017 at 7:47
  • except the values returned my .map are not being actually used - I said the way he uses .map he may as well use .forEach .... but .map is the right method if it is used correctly Commented May 21, 2017 at 7:48

2 Answers 2

7

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); 
Sign up to request clarification or add additional context in comments.

1 Comment

It worked, I learnt a new concept cause of you. Thanks a lot! :)
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.