For loop issue in MEAN node jS

87 views Asked by At

I am trying to send the response when the loop k value is equal to users[0].employees.length, but it's directly moving forward to max length, how do I solve it

 Userlist.find(queryObj).exec(function (err, users) {
            if (err) {
                return res.status(400).send({
                    message: errorHandler.getErrorMessage(err)
                });
            }
            else {
                console.log('found users list', users);
               // res.json(users[0].employees);
               var k=0;
               var resparr=[]
                for(var i=0;i<users[0].employees.length;i++){
                k++;

                    User.find({"_id":users[0].employees[i]._id}).exec(function(err,user){

                        resparr=resparr.concat(user);
                        console.log("resparray:",k,resparr.length,i,users[0].employees.length)
                        if(k==users[0].employees.length)
                        {

                            console.log("success",resparr)
                            res.json(resparr);

                        }   

                    })
                }

            }


        });
1

There are 1 answers

0
Lucas S. On BEST ANSWER

You are using an asynchronous function call within a synchronous loop. The loop will always finish before your callback functions are called.

You will need some kind of asynchronous looping. For a native solution you can use Promises:

const getUser = (id) => {
  return new Promise((resolve, reject) => {
    User.find({ '_id': id })
      .exec((err, user) => {
        if (err) reject(err);
        else resolve(user);
      });
  });
};

const promises = users[0].employees.map(({ _id: id }) => getUser(id));

Promise.all(promises)
  .then(users => res.json(users))
  .catch(err);

For utility packages in node.js, I'd recommend the package async for a callback based solution or bluebird for Promises. Both have a .map function which is perfect for this use case.