0

when I push an object into an array it works but outside of the function, it is empty again!

    .get(function(req, res){
    //Mongoose Model
    var employeeModel = require('../models/employeeModel');
    var employeeList = new Array();
    employeeItems = req.project.involvedEmployee;
    employeeItems.forEach(function(entry) {
        var employeeId = entry.employeeId;
        employeeModel.findById(employeeId, function(err, employee){
            if(err){
            res.status(500).send(err);
            }
            else {
                employeeList.push(employee);
            }                        
        });                          
    });
    res.json(employeeList);
});

Please tell me what is my problem?

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
Saeid Ostad
  • 667
  • 1
  • 11
  • 27
  • `findById` is **asynchronous**. You can't use the result where you're trying to use it, because at that point in time, the callbacks haven't happened yet. See the linked question's answers for details. – T.J. Crowder May 03 '17 at 16:47
  • @T.J.Crowder It similar but not exact duplicate, as there is multiple async callbacks that all need to complete before result can be used. – Pavel P May 03 '17 at 16:51
  • @Pavel: The concept still applies, it just need generalizing. And amusingly, as you were commenting, I was posting an answer over there for just this reason... :-) – T.J. Crowder May 03 '17 at 16:59
  • @Saeid: Since the linked duplicate didn't have an answer related to doing async calls for a *list* of things, I [posted one](http://stackoverflow.com/a/43766002/157247). Happy coding! – T.J. Crowder May 03 '17 at 17:00
  • I saw your posts but I am a little confuse, can you please write my code in right way? – Saeid Ostad May 03 '17 at 18:08

0 Answers0