2014-05-19 82 views
0

我正在構建一些自定義的社交共享圖標。我正在使用以下請求來計算每個網絡的共享,推文等。在「激活所有其他功能」部分下運行功能之前,我需要完成所有這些請求。按照我所擁有的方式嵌套它們,它迫使它們一次只運行一個。有沒有一種方法可以處理這些問題,使它們全部同時運行,並使底部的功能在所有功能都完成之前不會運行?如何同時運行這些功能?

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(); 
       }); 
      }); 
     }); 
    }); 
}); 

}

+5

http://api.jquery.com/jquery.when/會做你想要什麼 – jraede

+0

這正是我一直在尋找。你應該以答案的形式提出這個問題,以便我可以選擇它併爲它投票。 :-) –

回答

4

是包裹一切

$.when() 
要同時運行

,都是完整的,當他們,那麼這$.then()將執行

$.when( 
    // code to run, 
    // code to run , 
    //code to run, 
).then(function(){ 

    // runs when everything in top block is finished 
}); 

可以Google jQuery延期執行或jQuery承諾

+0

完美。這正是我所期待的。真棒。 –

0

另一種選擇是async.js庫。它還具有額外的好處,可以讓您將結果放入最終函數可以使用的對象中。從文檔

https://github.com/caolan/async

例子:

// 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} 
}); 

要與你的代碼中使用,你只要把你的getJSON通話到位setTimeout電話,放置callback函數內並通過成果轉化它。