Search code examples
javascriptangularjsangularjs-scopefactoryangular-promise

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.


Solution

  • 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;
                    });
                }
            }
        };
    });