简体   繁体   中英

AngularJS Cached Promise

I'm having an issue when the a promise is getting called before the data is returned from the factory. I have a factory that goes and retrieves as a list of states from a specified country.

The first time the controller is loaded it gets the list of states for the specified country properly. However, when the changeCountry function is called and the call to get a new states list is called, the promise resolves before the factory has a chance to return the data. In other words, the "then" is called before the "resolve", and the data is returned from the previous call.

Factory:

app.factory('localStates', ['$http', '$q', ($http, $q) ->
    # set deferred object for use later
    deferred = $q.defer()

    # get states
    get: (country_code) ->

        # query for list of states
        $http
           method: 'GET'
            url: '/api/areas'
            params:
                country_code: country_code
        .success (data, status) ->
            # send data through promise
            deferred.resolve data
        .error (data, status, headers, config) ->
            # send error data through promise
            deferred.reject data

    return deferred.promise

])

Controller

app.controller('LocalNumberCtrl', ['$scope', 'localCountries', 'localStates',($scope, localCountries, localStates) ->

    getStates = ->

        localStates.get($scope.LocalCountry).then (data) ->

            # set scope variable
            $scope.States = data

        , (data) ->
            # get states error

    # get local countries list
    localCountries.get().then (data) ->

        # set scope variable
        $scope.Countries = data

        # set default country
        $scope.LocalCountry = 'GB'

        # get list of states
        getStates()

     , (data) ->
         # get countries error

    $scope.changeCountry = ->

        getStates()
])

Any advice on how to get the second promise to not return the first promises data would be greatly appreciated. I'm not sure if there is something needed with a $timeout or some other way to clear the previous promise.

Thanks in advance.

I don't understand well coffescript, but i think you need create a new deferred object every times you call get function. Your javascript code should be something like this:

app.factory('localStates', ['$http', '$q', function($http, $q) {

    get: function(country_code) {

        var deferred = $q.defer()

        // remainder code 

        return deferred.promise;
    }

}]);

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