$scope.func1 = function() {
$http.get(url, {params}).success(function(result){
// code
}).error(function(error){
// error
})
}
$scope.func2 = function() {
$scope.func1();
// when http of func1 done executing, call following code
}
How do I check in func2 if http.get success of func1 is done executing?
By using promises properly you can chain multiple promises:
$scope.func1 = function () {
return $http.get(url, {/*params*/})
.then(function (response) { // success is deprecated, use then instead
// code
return something;
})
.catch(function (error) { // use catch instead of error
// error
});
};
$scope.func2 = function () {
$scope.func1().then(function(something) {
//when http of func1 done executing, call following code
});
};
Related
I have written a function wrapper that returns cached values for HTTP responses. In a specific situation (marked by comment // <--HERE) I see inconsistent behavior. I'm frankly not sure what exactly the inconsistency is, but bottom line, when the cache expires (has_expired), it does not wait for the http get to return in the recursive call.
My guess is I haven't put a "return" somewhere on a promise but I can't find out where (and why). Do I need to put a return in front of localForage.removeItem (and if so why?)
function cache_or_http(url,key) {
if (dont_use_cache()) {
return $http.get(url);
}
var d = $q.defer();
localforage.getItem(key)
.then (function(data) {
if (data) { // exists
if (has_expired(data.created_at)) {
localforage.removeItem(key)
.then (function() {return cache_or_http(url,key);}) // <--HERE
.catch(function() {return do_error_handling();})
} else { // not expired
d.resolve(JSON.parse(data.value));
return d.promise;
}
} else {
// doesn't exist
return $http.get(url)
.then (function(data) {
cache_entry = {
'value': JSON.stringify(data),
'created_at': moment().toString()
};
localforage.setItem(key, cache_entry);
d.resolve(data);
return (d.promise);
});
} // doesn't exist
}); // getItem .then
return (d.promise);
}
There is no need to manufacture a new promise with $q.defer. The .then method of a promise already returns a promise.
function cache_or_http(url,key) {
̶v̶a̶r̶ ̶d̶ ̶=̶ ̶$̶q̶.̶d̶e̶f̶e̶r̶(̶)̶;̶
̲r̲e̲t̲u̲r̲n̲ localforage.getItem(key)
.then (function(data) {
if (data) { // exists
if (has_expired(data.created_at)) {
̲r̲e̲t̲u̲r̲n̲ localforage.removeItem(key)
.then (function() {return cache_or_http(url,key);}) // <--HERE
.catch(function() {return do_error_handling();})
} else { // not expired
̶d̶.̶r̶e̶s̶o̶l̶v̶e̶(̶J̶S̶O̶N̶.̶p̶a̶r̶s̶e̶(̶d̶a̶t̶a̶.̶v̶a̶l̶u̶e̶)̶)̶;̶
return JSON.parse(data.value);
}
} else {
// doesn't exist
return $http.get(url)
.then (function(data) {
cache_entry = {
'value': JSON.stringify(data),
'created_at': moment().toString()
};
̲r̲e̲t̲u̲r̲n̲ localforage.setItem(key, cache_entry);
̶d̶.̶r̶e̶s̶o̶l̶v̶e̶(̶d̶a̶t̶a̶)̶;̶
̶r̶e̶t̶u̶r̶n̶ ̶(̶d̶.̶p̶r̶o̶m̶i̶s̶e̶)̶;̶
});
} // doesn't exist
}); // getItem .then
̶r̶e̶t̶u̶r̶n̶ ̶(̶d̶.̶p̶r̶o̶m̶i̶s̶e̶)̶;̶
}
For more information, see
Is this a "Deferred Antipattern"?
The past view days I read a lot of best practices in handling with promises. One central point of the most postings where something like this:
So if you are writing that word [deferred] in your code
[...], you are doing something wrong.1
During experimenting with the error handling I saw an for me unexpected behavior. When I chain the promises and It run into the first catch block the second promise gets resolved and not rejected.
Questions
Is this a normal behavior in other libs / standards (e.g. q, es6), too and a caught error counts as solved like in try / catch?
How to reject the promise in the catch block so that the second gets, called with the same error / response object?
Example
In this example you see 'I am here but It was an error'
Full Plunker
function BaseService($http, $q) {
this.$http = $http;
this.$q = $q;
}
BaseService.prototype.doRequest = function doRequest() {
return this.$http({
method: 'GET',
url: 'not/exisint/url'
})
.then(function (response) {
// do some basic stuff
})
.catch(function(response) {
// do some baisc stuff e.g. hide spinner
});
}
function ChildService($http, $q) {
this.$http = $http;
this.$q = $q;
}
ChildService.prototype = Object.create(BaseService.prototype);
ChildService.prototype.specialRequest = function specialRequest() {
return this.doRequest()
.then(function (response) {
alert('I am here but It was an error');
})
.catch(function (response) {
// do some more specific stuff here and
// provide e.g. error message
alert('I am here but It was an error');
return response;
});
}
Workaround:
With this workaround you can solve this problem, but you have to create a new defer.
BaseService.prototype.doRequest = function doRequest() {
var dfd = this.$q.defer();
return this.$http({
method: 'GET',
url: 'not/exisint/url'
})
.then(function (response) {
// do some basic stuff
dfd.resolve(response);
})
.catch(function(response) {
// do some basic stuff e.g. hide spinner
dfd.reject(error);
});
}
Your workaround is almost correct, you can simplify it to the following:
BaseService.prototype.doRequest = function doRequest() {
return this.$http({
method: 'GET',
url: 'not/exisint/url'
})
.then(function (response) {
// do some basic stuff
return response;
}, function (error) {
return this.$q.reject(error);
});
}
$q.reject is a shortcut to create a deferred that immediately get's rejected.
Yes, this is default behaviour in other libraries as well. .then or .catch simply wraps the return value into a new promise. You can return a rejected promise to make the .catch chain work.
You can also do the opposite, for instance when you want to reject the promise in the success callback for whatever reason:
function getData() {
return this.$http.get(endpoint).then(result => {
// when result is invalid for whatever reason
if (result === invalid) {
return this.$q.reject(result);
}
return result;
}, err => this.$q.reject(err));
}
getData().then(result => {
// skipped
}, error => {
// called
});
See example above
Just to add to Dieterg's answer and to your workaround, you can also wrap the code into $q constructor:
BaseService.prototype.doRequest = function doRequest() {
return $q(function (resolve, reject) {
$http.get('not/exisint/url').then(function (response) { // success
/* do stuff */
resolve(response);
}, function (error) { // failure
/* do stuff */
reject(error);
});
});
};
I have the following method getData(url) in a my factory which uses $http.get(url) to get data from an URL
angular
.module('az-app')
.factory('WebServiceFactory', function ($http, $q) {
var WebServiceFactory = this;
WebServiceFactory.getData = function (url) {
var deferred = $q.defer();
$http.get(url)
.then(
function (response) {
deferred.resolve({
data: response
});
}, function (rejected) {
deferred.reject({
data: rejected
});
}
);
//Promise to be returned
return deferred.promise;
}
It works fine but I need to abort the http.get and/or reject the promise so I can display an error message from my controller which has this method:
var getSpecialties = function (type) {
doctorsCtrl.showLoading();
var url = "example.com";
WebServiceFactory.getData(url)
.then(
function (result) {
doctorsCtrl.hideLoading();
var specialtiesArray = result.data.data;
StorageFactory.specialties = specialtiesArray;
doctorsCtrl.specialties = StorageFactory.specialties
//I WANT TO TRIGGER THIS REJECTED FUNCTION when timeout time is finished
}, function (rejected) {
doctorsCtrl.hideLoading();
doctorsCtrl.showAlert();
}
);
}
The service $http accepts, in the config object, a timeout property that answers to what you need. Have a look at the documentation, especially the part about the config object:
timeout – {number|Promise} – timeout in milliseconds, or promise that should abort the request when resolved.
Also, notice that you're using promises in an inefficient way. The following is a promise antipattern:
WebServiceFactory.getData = function (url) {
var deferred = $q.defer();
$http.get(url)
.then(
function (response) {
deferred.resolve(...);
}, function (rejected) {
deferred.reject(...);
}
);
//Promise to be returned
return deferred.promise;
}
You could have simply:
WebServiceFactory.getData = function (url) {
return $http.get(url);
}
With a timeout of 3 seconds it would be:
Service:
WebServiceFactory.getData = function (url) {
return $http.get(url, {timeout: 3000}); // <-- timeout applies ONLY for this call
}
Controller:
WebServiceFactory.getData(url).then(
function (result) {
doctorsCtrl.hideLoading();
doctorsCtrl.specialties = StorageFactory.specialties = result.data;
}, function (rejected) {
doctorsCtrl.hideLoading();
doctorsCtrl.showAlert();
}
);
Notice also that you're calling hideLoading both in case of success and error. You can call it once, in a chained finally handler:
// ...
.finally(function () {
doctorsCtrl.hideLoading();
}
Here is my service's response:
response = response.then(function (data) {
return data.data;
});
response.catch(function (data) {
$q.reject(data);
});
// Return the promise to the controller
return response;
In Interceptor I am returning:
return $q.reject();
But, still I am getting back into:
response.then
Is possible to get back into the catch block?
Thanks
Adding more code:
.service('APIInterceptor', function ($q, $rootScope, UserService) {
var service = this;
service.request = function(config) {
return $q.reject();
//return config;
};
service.responseError = function (response) {
return response;
};
})
What happens is that your .request creates an error (by doing return $q.reject()), but your .responseError "handles" that error (by virtue of being there), thus resulting in the overall successful resolution.
Indeed, removing .responseError handler makes the error bubble up to .catch. Alternatively, you can also return $q.reject() in .responseError.
I have a chain of promises that are responsible for initializing my controller. In this chain if a certain condition isn't met, it would be best to send the user to another state via $state.go() and stop the rest of the promise chain from running. How can this be accomplished?
loadData1()
.then(function(){
return loadData2();
})
.then(function(){
if (...) {
$state.go(...); // how should the existing promise chain be killed off or stopped?
}
else {
return loadData3();
}
})
.then(function(){
return loadData4();
})
.then(function(){
console.log('controller initialized successfully');
},
function(error){
console.log('failed to initialize controller');
});
Instead of immediately calling $state.go, throw an error and check for it in the error handler at the end.
loadData1()
.then(function () {
return loadData2();
})
.then(function () {
if (exceptionalCondition) {
throw new Error('[MyCtrl:loadData2] Data failed to load!');
}
return loadData3();
})
...
.then(function () {
console.log('controller initialized successfully');
},
function (error) {
if (/^\[MyCtrl:loadData2\]/.test(error.message)) {
$state.go(redirect);
} else {
console.log('failed to initialize controller');
}
});
The nice thing about using promises is that they will handle errors and immediately terminate the chain if one occurs.