Javascript Mongo异步调用

Javascript Mongo异步调用,javascript,ajax,mongodb,asynchronous,synchronous,Javascript,Ajax,Mongodb,Asynchronous,Synchronous,我有一条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.

我有一条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);
 });
但是下面的代码首先运行,因为用户找到了dbyid

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

如何使findById同步?

findById是专门设计用来接受回调或承诺的。因为它正在进行异步调用,所以它不会同步,所以您必须相应地重新构造代码