简体   繁体   中英

Node js array dashboard

I'm doing the backend of my app with node js. In this case i'm trying to get the typical dashboard like facebook, instagram,.... Where for one user i'm trying to get the users that he follows. And when i get the array of users following, i find the "recetas" that they have (one user can have more than one). And finally i add all this recetas in an array but the problem is that is returning me empty.

getDashboard = function (req, res) {
  var myarray = new Array();
  //myarray = [];
  User.findById(req.params.id, function (err, user) {
    if (!user) {
      res.send(404, 'User not found');
    }
    else {
      var a = user.following;
      a.forEach(function (current_value) {
        Receta.find({ "user_id": current_value._id }, function (err, recetas) {
          if (!err) {
            recetas.forEach(function (receta) {
              myarray.push(receta);
            }
          } else {
            console.log('Error: ' + err);
          }
        });
      })
      res.send(myarray);
    }
  });
};

You are dealing with a common async issue. Receta.find is asynchronous, it is not a blocking operation, so res.send is called before all of your Receta.find calls have completed. You can get around this issue by using Promises , assuming they are available in your version of Node:

var a = user.following;
var promises = a.map(function(current_value) {
    return new Promise(function(resolve, reject) {
        Receta.find({"user_id":current_value._id}, function (err, recetas) {
            if(!err) {
                resolve(recetas);
            } else {
                reject(err);
            }
        });
    });
});

Promise.all(promises).then(function(allData) {
    res.send(allData);
}).catch(function(error) {
    res.send(error);
});

If native Promises aren't available, you can use a library like Q or bluebird

res.send(myarray); is being called before a.forEach completes due to Receta.find which is I/O.

call res.send only when the loop is finished and recetas returned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM