Sunday, June 8, 2014

Ajax Multiple Requests

I was working on a scenario where I need to update the history of over 1000 records. While updating these records one by one I want to show the progress bar to keep the user informed of the progress. Ideally SignalR is the best for this situation. But I decided to do an ajax call from the browser. In this blog I will blog on how I did ajax for multiple requests. In the next blog I will blog on the progress bar.

On the technical stack, I am using SPA using Knockout and Durandal. For progress bar I am using the open source Kendo UI Core and on the server side I am using Web API.

I can update the history of these 1000 records in any order, in other words there is no dependency between these. For efficiency I decided to run these parallel as shown in the below flow chart.

How can I run these updates parallel in a synchronous manner without overloading the server? Luckily I don’t have to do anything. Browsers has a builtin mechanism for this. Most modern browsers do 4 to 6 parallel requests at a given time. If there are more requests they queue those requests. Using this behavior my code is very simple.

    function updateHistory(patients) {
        for (var index = 0; index < patients.length; index++) {
            var patientID = patients[index];
            utility.httpPost('api/compatupdatehistory', patientID).then(function (data) {
                    //show the progress bar

As you see, I am just looping through the list and calling my ajax post routine. I don’t need to do any recursion or any other mechanism for making multiple parallel ajax requests.

This mechanism works great if you have limited ajax requests, say 1000. If you want to do lot number of ajax requests then checkout Part 2 of this blog.

No comments:

Post a Comment