2011-07-28 39 views
3

在調用它們之前等待異步加載的類的正確方法是什麼?等待異步加載的類完成(無回調)

注意:我處於一個複雜的情況,我無法使用異步加載回調。

這是最好的辦法嗎?

callClassFunction : function() { 
    try { 
    waitingOnThisClass.someFunction(); 
    } catch (e) { 
    setTimeout("superClass.callClassFunction()",250); 
    } 
} 

* jQuery的方式也值得一提,如果有任何...

+1

什麼是'異步classes'? – davin

+0

@達文,修正了問題 – Kyle

回答

4

嘛。如果允許使用jQuery -jquery promise接口和jQuery.Deferred就是這樣的東西:

// Create a Deferred and return its Promise 
function asyncEvent(){ 
    var dfd = new jQuery.Deferred(); 
    setTimeout(function(){ 
     dfd.resolve("hurray"); 
    }, Math.floor(Math.random()*1500)); 
    setTimeout(function(){ 
     dfd.reject("sorry"); 
    }, Math.floor(Math.random()*1500)); 
    return dfd.promise(); 
} 

// Attach a done and fail handler for the asyncEvent 
$.when(asyncEvent()).then(
    function(status){ 
     alert(status+', things are going well'); 
    }, 
    function(status){ 
      alert(status+', you fail this time'); 
    } 
); 

另一個例子;

function doAjax(){ 
    return $.get('foo.htm'); 
} 

function doMoreAjax(){ 
    return $.get('bar.htm'); 
} 

$.when(doAjax(), doMoreAjax()) 
    .then(function(){ 
     console.log('I fire once BOTH ajax requests have completed!'); 
    }) 
    .fail(function(){ 
     console.log('I fire if one or more requests failed.'); 
    }); 
+0

非常感謝您的信息!週末過後,我得看看這個jQuery解決方案! – Kyle

+0

太棒了!不知何故,jQuery 1.5打破了我的平臺,但這肯定會在未來派上用場! – Kyle

+0

我很高興它幫助:)我在許多項目中使用deferreds - 當必須處理多個異步調用時,它們肯定會非常方便。 – ThatGuy

2

一個變化我會做是爲了擺脫try/catch語句,轉而測試是否存在功能(還):

callClassFunction : function() { 
    if (waitingOnThisClass && waitingOnThisClass.someFunction) 
    waitingOnThisClass.someFunction(); 
    else 
    setTimeout(superClass.callClassFunction,250); 
} 

請注意,您不需要明確說

if (waitingOnThisClass != undefined 
    && typeof waitingOnThisClass.someFunction === "function") 

因爲如果他們作爲對象/功能存在,他們會評估爲「truthy」。

(如果你使用一個try/catch和功能加載,但已在它的一些錯誤不會觸發捕捉,只是重新運行該功能再次重複?)

+0

這是真的嗎?我試着用Facebook的Javascript API'if if(FB)'和IE打破了FB說的沒有定義......就好像它只是在有條件的情況下打破了......我會嘗試在那裏添加函數並看看。謝謝!我會在星期一回到這個論壇 – Kyle

+0

+1非常感謝您使用try/catch指出問題 – Kyle