I want to use forEach (JavaScript in node js) to get values then store them as an array. But after the loop ends my array is empty or it is not stored. I don't know the cause of the problem, any help please.
Form1.find({}, function(err, alluser) {
if (err) {
res.redirect("back");
} else {
var usernames = []; // I want to store the values here
alluser.forEach(function(getuserid) {
var userids = getuserid.userid;
User.findById(userids, function(err, getnames) {
if (err) {
var nameitself = userids;
usernames.push(nameitself);
} else {
var firstname = getnames.firstName;
usernames.push(firstname);
console.log(usernames); // this returns the stored values at each iterations
}
});
})
console.log(usernames); // here I want the values but is empty [], I don't know the problem
res.send(usernames) // this also sends empty array
}
});