1

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
  }
});
imjared
  • 19,492
  • 4
  • 49
  • 72
wzwd
  • 169
  • 2
  • 10
  • this is an asynchronous call... you cannot return the values outside the callback... you have to return the `username` inside the callback of `findById` or use `async` `await`... – Ashh Jul 07 '18 at 16:28
  • 2
    I don't know about asynchronous call or I didn't use async await before. I will study about it. – wzwd Jul 07 '18 at 16:41

1 Answers1

0

The problem is you are thinking this code in terms of synchronous operation, i.e. line by line execution.

But in actual, the following line is accessing db so it is returning a callback

User.findById(userids, function(err, getnames)

Arghya Saha
  • 5,599
  • 4
  • 26
  • 48
  • Could you show how can I use asynchronous method for this problem?. I have many codes with similar problem. If you could help me to solve this, I can easily understand about asynchronous and solve my problem. I am reading about asynchronous but yet I didn't understand it. – wzwd Jul 08 '18 at 18:53