Suppose I have three functions as such:
function A() {
//does a jquery getJson() request and applies json data to html
function C()
}
function B() {
//does a jquery getJson() request and applies json data to html
function C()
}
function C(){
// applies cosmetic changes to the already set html which was made be Functions A & B.
//for example it converts numbers 1-5 set in a span to starred rating.
}
The problem is that the functions A and B are async and their callback execution depends on the time taken of reception of json. and thus calling function C fails on one or the other dataset received by json.
So what I want is that function C should be executed ony after both the jsons are received and its data plotted onto the page. and it has to be called only once.
I have a feeling that this may be possible by closures but I am not sure.
You could use the Deferred Object which deals with asynchronous calls for you. Doing so your code will be executed in the reading order, no matter when the response is sent back :
var jqxhr = $.getJSON('url', function(data) {
alert('first callback');
});
jqxhr.done(function() {
alert('second callback');
});
Then use jQuery.when() to handle multiple deferred :
var jqxhr1 = $.getJSON('url1');
var jqxhr2 = $.getJSON('url2');
$.when(jqxhr1, jqxhr2).done(function(data1, data2) {
alert('both done');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With