我已经阅读了Kris Kowal的Q和angularjs $ q变量几个小时了。但是对于我的一生,我无法弄清楚它是如何工作的。

目前,我的服务中包含以下代码:

resetpassword: function (email, oldPassword, newPassword) {

                var deferred = $q.defer(); //Why am I doing this?
                var promise = auth.$changePassword(email, oldPassword, newPassword); //$changepassword in angularfire returns a promise
                console.log(deferred); //Object with resolve, reject, notify and promise attrs
                var rValue = promise.then(function(){
                        //successcallback
                        return 1; //if changepassword succeeds it goes here as expected
                    }, function(error){
                        //errorcallback
                        return error.code; //if changepassword fails (wrong oldpass for example) it goes here, also works
                    }
                );
                deferred.resolve(promise); //Should I do this? I thought my promise was resolved in the callbacks?
                console.log(rValue); //This outputs another promise? Why not 1 or error.code, how the am I ever going to get these values??
                return rValue; //I want 1 or error.code to go back to my controller
            },

最佳答案

var deferred = $q.defer(); //Why am I doing this?


您正在执行的deferred anti-pattern是因为您不了解承诺。从字面上看,从来没有很好的理由在应用程序逻辑中使用$q.defer()

您需要从函数中返回一个承诺:

resetpassword: function(email, oldPassword, newPassword) {
    return auth.$changePassword(email, oldPassword, newPassword)
           .then(function() { return 1; })
           .catch(function(e) { return e.code });
}


用法是:

resetpassword(...)
.then(function(num) {
    if (num === 1) {

    }
    else {

    }
});




可以考虑如何用同步代码编写函数:

 resetpassword: function(email, oldPassword, newPassword) {
     try {
         auth.$changePassword(email, oldPassword, newPassword)
         return 1;
     }
     catch (e) {
         return e.code;
     }
 }

07-24 09:17