简体   繁体   English

如何解决$ q的承诺?

[英]how to resolve a $q for promise?

I'm using AngularJS and $q for promises, I'm confuse with the usage, How can I fix this promise? 我正在使用AngularJS和$ q作为承诺,我对使用感到困惑,我该如何解决这个承诺?

I want to return the user when isLoggedInPromise() is called or a "AUTH_REQUIRED". 我想在调用isLoggedInPromise()或“AUTH_REQUIRED”时返回用户。

Thanks! 谢谢!

    function isLoggedInPromise() {
        $q.when(userWithAllData()).then(function(user) {
            return user;
        });
        $q.when(userWithAllData()).reject(function() {
            return "AUTH_REQUIRED";
        });
    }

    function userWithAllData(){
        var deferral = $q.defer();

        var query = new Parse.Query(Parse.User);
        query.include(["info", "info.rank", "privateInfo"]);
        query.get(Parse.User.current().id).then(function (loadedUser){
            deferral.resolve( loadedUser );
        });

        return deferral.promise;
    }

What you want to do is call the resolve function on the promise when the function has all the data it needs to actually return 当函数具有实际返回所需的所有数据时,您要做的就是在promise上调用resolve函数

in a function that returns a promise, think of "resolve" as the actual return statement. 在返回promise的函数中,将“resolve”视为实际的return语句。

so your isLoggedInPromise function needs to return a promise as well which will kind of make it redundant. 所以你的isLoggedInPromise函数也需要返回一个promise,这会使它变得冗余。 Anything that needs a user will have to wait for it via then. 任何需要用户的东西都必须等待它。

isLoggedInPromise().then(function(result){...etc...}, function(reason){//auth needed})

If you still need the isLoggedin Function then it should look like 如果你仍然需要isLoggedin函数,那么它应该是这样的

 function isLoggedInPromise() {
    var isLoggedIn = userWithAllData().then(
        function(user) {
            return user;
        }, 
        function(reason){
            return $q.reject("AUTH_REQUIRED")
        });    
 }

of course you'll have to include some rejection logic in the userWithAllData function as well. 当然,您还必须在userWithAllData函数中包含一些拒绝逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM