Programming pattern to flatten deeply nested ajax callbacks?
- by chiborg
I've inherited JavaScript code where the success callback of an Ajax handler initiates another Ajax call where the success callback may or may not initiate another Ajax call. This leads to deeply nested anonymous functions. Maybe there is a clever programming pattern that avoids the deep-nesting and is more DRY.
jQuery.extend(Application.Model.prototype, {
process: function() {
jQuery.ajax({
url:myurl1,
dataType:'json',
success:function(data) {
// process data, then send it back
jQuery.ajax({
url:myurl2,
dataType:'json',
success:function(data) {
if(!data.ok) {
jQuery.ajax({
url:myurl2,
dataType:'json',
success:mycallback
});
}
else {
mycallback(data);
}
}
});
}
});
}
});