I am trying to create a queue of functions to be called to return autocomplete results. Some of them are functions I construct myself from $.getJSON calls and some are provided to me by external developer using what's specified for jQuery UI autocomplete.
For example, here's a fake one provided. I don't know up front if it's truly async or when it might call the callback:
var providedFunction = function(search, response) {
setTimeout(function() {
var arr = ['One', 'Two', 'Demo Custom'];
response($.grep(arr, function (s) { return s.indexOf(search) === 0; }));
},5000);
};
Then I want to combine it with some number of other $.getJSON calls and not continue until the whole list has finished:
var searchTerm = "Demo";
var allResults = [];
var functionQueue = [];
functionQueue.push(
$.getJSON( 'http://ws.geonames.org/searchJSON?featureClass=P&style=short&maxRows=50&name_startsWith=' + searchTerm)
.success( function(data) {
$.each(data.geonames, function(i,d) {
allResults.push(d.name); });
})
);
functionQueue.push(
providedFunction(searchTerm, function(data) {
allResults.push.apply(allResults, data);
})
);
// wait for all asyc functions to have added their results,
$.when.apply($, functionQueue).done(function() {
console.log(allResults.length, allResults);
});
The problem is that $.when does not wait for the provided function to complete. It returns as soon as all $.getJSON calls have completed. So clearly I'm not wiring up the provided function correctly, but I'm not sure how to do it.