Created
August 16, 2014 06:24
-
-
Save pulakb/94d9d1c96e77537c304e to your computer and use it in GitHub Desktop.
Use promise with a recursive function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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