JSFiddle - React, Tailwind, and code Playground
by PeterShafer
HTML
<div ng-app="angularApp">
<pre ng-controller="Demo as demo">
{{ demo.content }}
</pre>
</div>
JavaScript
angular.module('angularApp', [])
// A service to cache data from a request to a web server
.service('serialRequest', function serialRequest($http, $q, $timeout) {
/* Junk for faking conditions. */
var timesCalled = {};
var timeout = 2000;
/* End of that junk. */
return {
get: function(url){
// Internal function for making requests.
function makeRequest(url){
$http.get(url).then(function(data){
/* More fake condition junk. */
timesCalled[url] = timesCalled[url] || 0;
timesCalled[url]++;
/* End of that junk. */
// Check condition to see if data is returned.
if(timesCalled[url] > 3){
deferred.resolve(data);
}else{
// Otherwise, wait, then try again.
$timeout(function(){ makeRequest(url); }, timeout);
}
}, function(data){
deferred.reject(data);
});
}
var deferred = $q.defer();
// Kick off the loop of requests.
makeRequest(url);
// Return the promise that some day we'll finish looping.
return deferred.promise;
}
};
})
// This second controller will display the status of the cached data.
.controller('Demo', function demo(serialRequest) {
var self = this;
serialRequest.get("https://randomuser.me/api/").then(function(data){
self.content = data.data.results[0].email;
});
})