hmmm probably I'm in need of some javascript knowledge because, how can this piece of code not fire three Ajax requests?
var getName = function() {
var name = null;
var deferred = $q.defer();
if (name !== null) deferred.resolve(name);
$http.get('https://api.github.com/users/peterbe')
.success(function(data) {
deferred.resolve(data.name);
}).error(deferred.reject);
return deferred.promise;
};
When called three times with the $timeout, the name variable is local to the function and it gets set every call to null. So that would mean that this condition is always false?
if (name !== null) deferred.resolve(name);
Meaning no caching is happening here, I know it's not the main subject of this article but still.
Correct me if I'm wrong.
Thanks J
If you make that 'var name' global instead and assign to it inside the success callback you'll be fine. But also, you'll need to put the $http.get in an else block.
Comment
hmmm probably I'm in need of some javascript knowledge because, how can this piece of code not fire three Ajax requests?
var getName = function() {
var name = null;
var deferred = $q.defer();
if (name !== null) deferred.resolve(name);
$http.get('https://api.github.com/users/peterbe')
.success(function(data) {
deferred.resolve(data.name);
}).error(deferred.reject);
return deferred.promise;
};
When called three times with the $timeout, the name variable is local to the function and it gets set every call to null. So that would mean that this condition is always false?
if (name !== null) deferred.resolve(name);
Meaning no caching is happening here, I know it's not the main subject of this article but still.
Correct me if I'm wrong.
Thanks J
Replies
If you make that 'var name' global instead and assign to it inside the success callback you'll be fine.
But also, you'll need to put the $http.get in an else block.