2014-02-25 239 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();