2010-11-20 1 views
4

mongoose를 사용하여 두 가지 다른 쿼리가 완료된 후 콜백을 보내고 싶습니다. mongoose를 사용하여 두 개의 비동기 쿼리를 완료 한 후 콜백이 발생했습니다

 
var team = Team.find({name: 'myteam'}); 
var games = Game.find({visitor: 'myteam'}); 

다음 방법 체인 및/또는 내가 이러한 요청이 아닌 차단을 원하는 비동기 적으로 실행 가정 약속에서 사람들이 개 요청을 포장?

나는 다음과 같은 차단 코드를 피하기 위해 싶습니다

:

 
team.first(function (t) { 
    games.all(function (g) { 
    // Do something with t and g 
    }); 
}); 

답변

12

같은 것을보고 싶지 생각을 당신이 이미 해결책을 찾았지만 어쨌든 생각합니다. async 라이브러리를 쉽게 사용할 수 있습니다. 이 경우 코드는 다음과 같이 표시됩니다.

async.parallel(
    { 
     team: function(callback){ 
      Team.find({name: 'myteam'}, function (err, docs) { 
       callback(err, docs); 
      }); 
     }, 
     games: function(callback){ 
      Games.find({visitor: 'myteam'}, function (err, docs) { 
       callback(err, docs); 
      }); 
     },      
    }, 
    function(e, r){ 
     // can use r.team and r.games as you wish 
    } 
); 
+0

매우 멋진 답변 –

관련 문제