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
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 -
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 -
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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