用猫鼬嵌套承诺

时间:2014-02-25 06:56:22

标签: node.js mongodb mongoose promise

我承诺我正在使用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();
    }

);

1 个答案:

答案 0 :(得分:0)

你似乎误解了一些关于Promises的事情:

鉴于getTeamPromise.then(onResolve, onReject)

  • 在onResolve和onReject中,承诺已经解决/拒绝,因此您无法通过在同一承诺上调用resolve来改变其状态
  • 你的决心(function())应该是第一个结果的处理结果
  • 通常你不应该操纵承诺的状态,你调用的很多方法都是创建和完成承诺的内部方法。
  • 从onResolve处理程序返回一个promise会将该promise或值传递给下一个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();