I am writing some Javascript/jQuery code that requires me to make lots of requests to various APIs. I have come across this problem many times and this is just a basic example of one instance of it.
The code makes an asynchronous request to a server and then if a condition with the returned data is not met, the code makes another request. The second request has a callback that contains much of the same logic as its parent. I know that I am avoiding repetition by calling the returnFunction
in each callback but is there a way to avoid this altogether?
var container = [];
$.getJSON("http://www.url.com/api/?callback=?",
{ data: "mydata" },
function(data) {
if(!data.length) {
// No results
} else {
// Put the results into an array
$(data).each(function(k, v){
container.push(v.some_data);
});
// If the query did not return enough results
if(data.length < limit) {
var number_missing = limit - data.length;
// Get some more results and append to the array
myFunctionToGetSomethingElse(number_missing, function(response){
// Add these results to the array
$(response).each(function(k, v){
container.push(v.some_data);
});
// Do something with this data
returnFunction(response);
});
} else {
// Do something with the result
returnFunction(data);
}
}
});
How would you recommend I avoid the repetition of the code inside the callbacks? Is this the only possible way?