我承诺我正在使用mongoose进行数据库操作。使用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();
}
);
答案 0 :(得分:0)
你似乎误解了一些关于Promises的事情:
鉴于getTeamPromise.then(onResolve, onReject)
:
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();