2014-02-25 270 views
0

我有一個承諾,我正在使用貓鼬做數據庫操作。使用mpromise庫,我正在使用teamMatch並使用它來更新Team文檔。但是,該程序不會在我更新Team(開始於var getTeamPromise)之後執行任何操作。嵌套承諾與貓鼬

如何更改此代碼以便我可以更輕鬆地執行上述操作?

saveTeamMatch.then(

    function saveTeamMatchToTeam(teamMatch) { 

     console.log('TEAM_MATCH in SAVE to TEAM', teamMatch); //works 

     // when a team is gotten and a teamMatch is made and saved 
     // save the teamMatch to the team 
     var getTeamPromise = Team.findOneAndUpdate({ id:1540 }, { $push:{ matches:teamMatch } }).exec() 

     .then(

      function successfullySaveTeamMatchToTeam(team) { 
       console.log('TEAM in SUCCESSFUL SAVE', team); 
       getTeamPromise.resolve(); 
      }, 

      function failToUpdateTeam(err) { 
       console.error(err); 
       getTeamPromise.resolve(); 
      } 

     ) 

     .resolve(
      function endFindMatchPromise() { 
       saveTeamMatch.end(); 
      } 
     ); 
    }, 

    function failToSaveTeamMatch(err) { 
     console.error(err); 
     saveTeamMatch.end(); 
    } 

); 
+1

什麼'.resolve ()'應該這樣做? – Bergi

回答

0

看來你誤解了有關承諾的一些事情:

鑑於getTeamPromise.then(onResolve, onReject)

  • 在onResolve和onReject承諾已經解析/拒絕,因此你不能改變其狀態通過調用相同承諾上的解析
  • 您的解決方案(函數())應該是第一個然後
  • 通常你不應該操縱承諾的狀態,你調用的很多方法都是用於創建和滿足承諾的內部方法。
  • 返回一個承諾從onResolve處理器將管許諾或值到下一個then

讓我在寫這一點 - 也許 - 工作方式:

saveTeamMatch.then(function saveTeamMatchToTeam(teamMatch) { 
    console.log('TEAM_MATCH in SAVE to TEAM', teamMatch); //works 
    // when a team is gotten and a teamMatch is made and saved 
    // save the teamMatch to the team 
    return Team 
     .findOneAndUpdate({id:1540}, {$push:{matches:teamMatch}}).exec() 
     .then(function successfullySaveTeamMatchToTeam(team) { 
      console.log('TEAM in SUCCESSFUL SAVE', team); 
      return team; 
     }, function failToUpdateTeam(err) { 
      console.error('failedToUpdateTeam', err); 
     }); 
},function failToSaveTeamMatch(err) { 
    console.error('saveTeamMatch failed', err); 
}) 
.end();