Skip to content

Instantly share code, notes, and snippets.

@pulakb
Created August 16, 2014 06:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pulakb/94d9d1c96e77537c304e to your computer and use it in GitHub Desktop.
Save pulakb/94d9d1c96e77537c304e to your computer and use it in GitHub Desktop.
Use promise with a recursive function
<!DOCTYPE html>
<html>
<head>
<title>Use promise with a recursive function</title>
<script src="q.js"></script>
<script src="jquery-2.1.1.min.js"></script>
<script>
var loadCount = 0;
var newSectionArray = [];
function section(deferred) {
if(!deferred){
deferred = Q.defer();
}
var apiURL = "/data/" + "sports" + loadCount + ".json";
$.ajax( {
url: apiURL,
dataType: 'json',
success: function(result) {
loadCount++;
newSectionArray.push(result);
if(loadCount < 3) {
section(deferred);
} else {
loadCount = 0;
deferred.resolve(newSectionArray);
}
},
error: function (jqXHR, textStatus, errorThrown) {
return deferred.reject();
}
});
return deferred.promise;
};
section().then(function (response) {
console.log(response);
}, function (reason) {
console.log(reason);
});
</script>
</head>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment