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

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks but now, somehow I get passed it and will fire the API calls even when the promise is not resolved.
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; }); } 

1 Comment

Thanks but the same issue in here as well, I need the value of division not to be null before calling fooServices.getData().

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.