简体   繁体   中英

angular factory store promise result

I have a factory object that contain private object, which is used to cache result retrieved from the api using the factory available functions.

global.mainApp.factory('SessionFactory', function (UserEndpointsResource, SiteEndpointsResource) {
    var data = {
        /**
         * @type {boolean|null}
         */
        isLoggedIn: null
    };
    return {
        isUserLoggedIn: function (callback) {
            if (data.isLoggedIn != null) {
                callback(data.isLoggedIn);
            }
            else {
                UserEndpointsResource.isLoggedIn().$promise.then(function (res) {
                    var isUserLoggedIn = res.status == 1;
                    // Trying to set the result to the outer scope data variable
                    data.isLoggedIn = isUserLoggedIn;
                    callback(isUserLoggedIn);
                }, function (failureData) {
                    data.isLoggedIn = false;
                    callback(false);
                });
            }
        },
        ...
    };
});

The problem that every time I call the isUserLoggedIn function, data.isLoggedIn is always null.

How can I alter the factory data object inside the promise then function?

Thanks.

Using the suggestion supplied in the comments, aka do not store promise results, store promises themselves , this is the modified working code!

global.mainApp.factory('SessionFactory', function (UserEndpointsResource, SiteEndpointsResource) {
    var data = {
        /**
         * @type {boolean|null}
         */
        isLoggedIn: null
    };
    return {
        isUserLoggedIn: function (callback) {
            if (data.isLoggedIn != null) {
                data.isLoggedIn.then(function (isLoggedIn) {
                    callback(isLoggedIn.status == 1);
                });
            }
            else {
                data.isLoggedIn = UserEndpointsResource.isLoggedIn().$promise.then(function (res) {
                    var isUserLoggedIn = res.status == 1;
                    callback(isUserLoggedIn);
                    return isUserLoggedIn;
                }, function (failureData) {
                    data.isLoggedIn = false;
                    callback(false);
                    return null;
                });
            }
        }
    };
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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