Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

then function is not defined

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

like image 656
Afflatus Avatar asked Jun 22 '26 11:06

Afflatus


2 Answers

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.

like image 82
fracz Avatar answered Jun 24 '26 01:06

fracz


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;
    });
}
like image 33
karaxuna Avatar answered Jun 24 '26 02:06

karaxuna