Mongo 异步调用

Mongo Asynchronous Call

我有这条Ajax路线:

router.get('/getThey', middleware.isLoggedIn, function(req, res){
var array = [];
var followingLength = req.user.they.length -1;


req.user.they.forEach(function(userId, i){
  User.findById(userId, function(err, foundUser){
    foundUser.theySent.forEach(function(theySent, i){
      var foundLength = foundUser.theySent.length -1;

      while(i !== foundLength){
        if(req.user.notifications.indexOf(theySent) === -1){
          req.user.notifications.push(theySent);
          req.user.save();
        }
      }
    });
  });
 }); 

 res.json(req.user.notifications);
 });

但下面的代码首先运行,因为 User findById

if(aux === true && i === followingLength){
  res.json(req.user.notifications);
}

我该怎么做才能使 findById 同步?

findById 专门设计用于回调或承诺。由于它正在进行异步调用,因此不会同步,因此您必须相应地重组代码。