Tuesday, February 18, 2014

jQuery - waiting for multiple AJAX requests to finish

Problem I am solving -

Wait for N or Multiple or Unknown number (Depends on some logic) of ajax request using JQuery to complete, i.e.

$.when(N ajax request).then(do something)

Lets take a look at easier version of the problem, what if we want to wait for only two calls
class Test
waitForTwoCalls: () ->
$.when(@firstCall(), @secondCall()).then () =>
doSomeThing()
firstCall: () ->
token = $.Deferred
$.ajax({
url: foo/bar,
....
success: (response) =>
token.resolve
})
secondCall: () ->
token = $.Deferred
$.ajax({
url: foo/bar,
....
success: (response) =>
token.resolve
})


Well that was easy, so what... huh

What if you wana wait for n number of calls ? You cannot do $.when(call1, call2, ....., calln).then...

Lets take a look at a use case -

Lets say there is an array of ids and for each id in the array, we gota make a call and when all the data is loaded, we want to show a big red BLINK.

Here is how we gona do this -

# Makes ajax req to fetch data
class Model
initialize(id)
@id = id
load: (token) ->
$.ajax({
url: "foo/bar/#{@id}",
....
success: (response) =>
token.resolve
})
class Test
waitForNCalls: (ids) ->
tokens = []
for id in ids
token = $.Deferred
loader = new Model(id)
loader.load(token)
tokens.push(token)
return tokens
# Here is where the magic happens, it waits for all the tokens to get resolved
$.when.apply(this, @waitForNCalls([1,2,3....N])).done( =>
# Show RED BLINK
)

No comments:

Post a Comment