Reputation: 964
I'm working on building some custom social sharing icons. I'm using the following requests to get the count of shares, tweets, etc. from each network. I need all of these requests to be complete prior to running the functions under the "Activate All Other Functions" section. By nesting them the way that I have, it forces them to run one at a time. Is there a way that I can process these such that they all run simultaneously and so that the functions at the bottom do not run until they are all complete?
function getShares($URL) {
// Get the Twitter Share Count
jQuery.getJSON('http://cdn.api.twitter.com/1/urls/count.json?url=' + $URL + '&callback=?', function (twitdata) {
jQuery('.twitter .count').text(ReplaceNumberWithCommas(twitdata.count));
// Get the LinkedIn Count
jQuery.getJSON('http://www.linkedin.com/countserv/count/share?url=' + $URL + '&callback=?', function (linkdindata) {
jQuery('.linkedIn .count').text(ReplaceNumberWithCommas(linkdindata.count));
// Get Facebook Shares
jQuery.getJSON('http://graph.facebook.com/?id=' + $URL + '&callback=?', function (facebook) {
jQuery('.fb .count').text(ReplaceNumberWithCommas(facebook.shares));
// Get Pinterest Pins
jQuery.getJSON('http://api.pinterest.com/v1/urls/count.json?url=' + $URL + '&callback=?', function (pins) {
jQuery('.nc_pinterest .count').text(ReplaceNumberWithCommas(pins.count));
// Get Pinterest Pins
jQuery.getJSON('http://api.pinterest.com/v1/urls/count.json?url=' + $URL + '&callback=?', function (pins) {
jQuery('.nc_pinterest .count').text(ReplaceNumberWithCommas(pins.count));
// Activate All Other Functions
createFloatBar();
setWidths();
floatingBar();
activateHoverStates();
});
});
});
});
});
}
Upvotes: 0
Views: 124
Reputation: 1619
Another option is the async.js library. It has the added benefit of allowing you to put the results into an object that the final function can use.
https://github.com/caolan/async
Example from the documentation:
// an example using an object instead of an array
async.parallel({
one: function(callback){
setTimeout(function(){
callback(null, 1);
}, 200);
},
two: function(callback){
setTimeout(function(){
callback(null, 2);
}, 100);
}
},
function(err, results) {
// results is now equals to: {one: 1, two: 2}
});
To use with your code, you just put your getJSON
calls in place of the setTimeout
calls, placing the callback
function within and passing the results into it.
Upvotes: 0
Reputation: 9570
yes wrap everything in
$.when()
that you want to run simultaneously, when they are all complete , then this $.then()
will execute
$.when(
// code to run,
// code to run ,
//code to run,
).then(function(){
// runs when everything in top block is finished
});
you can Google jQuery Deferred Execution , or jQuery promise
Upvotes: 4