3

I have a function to get the current company code which I need to store on localstorage and use it in the rest of API calls. so until the value of this company code is not retrieved, I shouldn't make the API calls. This is how I get the company code

currentDivision = function() {
    var q = $q.defer();
    var division = window.localStorage.getItem("CurrentDivision");
    if(division){
        return q.resolve(division);
    }
    else{
        var url = this.fooApi + "current/Me?$select=CurrentDivision";
        $http.get(url)
            .success(function(data) {
                division = data.d.results[0].CurrentDivision;
                window.localStorage.setItem("CurrentDivision", division);
                return q.resolve(division);
            })
    }
    return q.promise;
}

and this is how I try to call the rest of the API calls after making sure the current division is retrieved successfully:

$scope.openModal = function() {
        $scope.modal.show().then(function() {
            currentDivision().then(function(){
            fooServices.getData().then(function() {
                $scope.closeModal();
            }, function(reason) {
                // handle the error
                $scope.showAlert(reason);
                $scope.closeModal();
            })
            });
        })
}

but as I try this on, I get this error message: TypeError: Cannot read property 'then' of undefined

Afflatus
  • 933
  • 1
  • 12
  • 39
  • Possible duplicate of [TypeError: Cannot read property 'then' of undefined](http://stackoverflow.com/questions/24788171/typeerror-cannot-read-property-then-of-undefined) – fracz Feb 10 '16 at 07:16

2 Answers2

1

You should always return q.promise. Remove the return in:

if (division) {
    return q.resolve(division);
}

I.e.:

var q = $q.defer();
// ...
if (division) {
    q.resolve(division);
} else { 
  //...
}
return q.promise;

In this way you are returning already resolved promise, which calls then immediately.

fracz
  • 20,536
  • 18
  • 103
  • 149
  • Thanks but now, somehow I get passed it and will fire the API calls even when the promise is not resolved. – Afflatus Feb 10 '16 at 07:15
1

Try this:

if (division) {
    return $q.when(division);
}

And improve your code:

currentDivision = function () {
    if (division) {
        return $q.when(division);
    }

    var url = this.fooApi + "current/Me?$select=CurrentDivision";
    return $http.get(url).then(function (data) {
         division = data.d.results[0].CurrentDivision;
         window.localStorage.setItem("CurrentDivision", division);
         return division;
    });
}
karaxuna
  • 26,752
  • 13
  • 82
  • 117
  • Thanks but the same issue in here as well, I need the value of division not to be null before calling fooServices.getData(). – Afflatus Feb 10 '16 at 07:39