我承诺我将使用猫鼬进行数据库操作。使用 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();
    }

);
有帮助吗?

解决方案

看来您误解了 Promise 的一些内容:

给定 getTeamPromise.then(onResolve, onReject):

  • 在 onResolve 和 onReject 中,promise 已经被解析/拒绝,因此你不能通过对同一个 Promise 调用解析来改变它的状态
  • 您的resolve(function())应该是第一个then结果的处理结果
  • 通常,您不应该操纵 Promise 的状态,并且您调用的许多方法都是用于创建和履行 Promise 的内部方法。
  • 从 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();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top