Eterm
Eterm

Reputation: 1808

Why don't these $.getJSON calls return in parallel?

<script type="text/javascript">
    var sourceData = {sites:[{ name: "London" , Id: "0"}, { name: "Bath", Id: "1"}, { name: "Cambridge", Id: "2"}]};
    $(document).ready(function () {
    $(sourceData.sites).each(function (index, data) { var objName = "<div class='bold' id = place" + data.Id + ">" + data.name + "</div>"; $('#results').append(objName); });

    $(sourceData.sites).each(function (index, data) {
    $.getJSON("GenerateData.aspx?place=" + data.name, function (retData) {
            $('#place' + data.Id)
                .wrap("<a href=GenerateData.aspx?place=" + data.name + "></a>")
                .append(retData.Wait); });
        });
    });
</script>

So basically generateData just returns a json which looks like:

{"name": "(place parameter passed back)", "Wait": 5000}

Except 5000 is actually Rand(0,5000) and also corresponds to a thread.sleep that executes before the request is returned.

What I can't understand is that while I'm getting some parallelisation (the order in which results are returned is random), the order in which they return is not from lowest to highest, and also the total return time is equal to the total wait times.

So there's no actual parallelisation of the requests against GenerateData, even though the requests seem to be sent out in parallel.

I've seen Asynchronous Controller is blocking requests in ASP.NET MVC through jQuery but that seems specific to MVC which I'm not using (yet).

Am I doing anything wrong from the jquery side, or is this another case of ASP.net sessions messing parallelisation up?

look at the latencies in the javascript console

Upvotes: 0

Views: 372

Answers (1)

Konstantin Dinev
Konstantin Dinev

Reputation: 34905

It's not a coincidence that $.getJSON() is an asynchronous operation. The requests responses are not going to be ordered in the same way the requests are or at least very rarely they will. If you want your requests to return in the order that you sent them then you need to create an Ajax queue and then the requests would be sent upon completion of previous requests. You can achieve this using jQuery.queue().

Upvotes: 1

Related Questions