Home Ask Login Register

Developers Planet

Your answer is one click away!

Troy Daniels February 2016

Consistent ordering of Ajax results

I have Coffeescript code running in playframework which builds a table based on several AJAX queries.

$ ->
    $.get "/queues", (queues) ->
        $.each queues, (index, queue) ->
            $.get "/queue/" + queue, (html) ->
                $("#queues").append $("<tr>").html html

/queues returns a list of queue names.
/queue/name returns HTML describing queue name.
#queues is a table, where I display that description.

This all works fine, but since the queries are asynchronous, the append calls are executed in a different order each time, which means that the table contents are randomly reordered every time the query runs. Since this is providing the current status of a dynamic, the query runs every three seconds.

What is a good way to have the rows be displayed in a consistent order every time? I have index, so I could try adding the data into that row, but if the third query returns first, adding it to row three is not going to work well.

I do not have a strong preference about how the ordering is done, just that it is consistent over multiple loads.


TimK February 2016

One option would be to force the queries to be sequential. For example, define a recursive function to get the results of one query before making the next one:

do_queue = (index, queues) ->
    if index >= queues.length then return
    queue = queues[index]
    $.get "/queue/" + queue, (html) ->
        $("#queues").append $("<tr>").html html
        do_queue(index+1, queue)

Then call it like this:

$ ->
    $.get "/queues", (queues) ->
        do_queue(0, queues)

Post Status

Asked in February 2016
Viewed 1,805 times
Voted 9
Answered 1 times


Leave an answer

Quote of the day: live life