1

I have a situation in which I am executing multiple async javascript Ajax request inside a for loop and getting result in json array of object asynchronously(not in a sequences) and then I have to cancat those array to make a single array.

So my questions is how can I sort the final array after getting last results of request raised from a loop and publish first record from array? Because I am getting result asynchronously so I don't know which request will be processed at last? And I can't use sync ajax request.

Thanks

1 Answers1

0

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.

Charlie Martin
  • 8,208
  • 3
  • 35
  • 41