The best way to do this is with Promises.
Promise.all([
$.get('...url1'),
$.get('...url2')
]).then(onSuccess, onFailure);
function onSuccess(resultOfAllRequests) {
// do something with the results of all requests
// this won't be executed until all asynch requests are complete
var resultOfRequest1 = resultOfAllRequests[0];
var resultOfRequest2 = resultOfAllRequests[1];
var singleArrayOfAllResponses = Array.prototype.concat.apply(Array.prototype, resultOfAllRequests);
var sorted = singleArrayOfAllResponse.sort(function (a, b) {
// this is numeric sorting. use your own sort logic
return a - b;
});
var first = sorted[0]; // <-- this is what you wanted
}
function onFailure(resultOfAllRequests) {
// one or many of the requests failed
// handle the error(s) here
}
Note: Promises are not currently supported in Internet Explorer. Here is the complete list of browser support. There are many libraries that implement Promises for you that you can use if you need IE support. Most notably q. Angular.js also has its own promise implementation called $q.