簡體   English   中英

等待異步加載的類完成(沒有回調)

[英]Wait for async loaded classes to finish (without callback)

在調用類之前等待異步加載的類的正確方法是什么?

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

這是最好的方法嗎?

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

* jQuery的方式值得一提,如果有的話......

好。 如果允許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.' );
   });

我要做的一個改變是擺脫try / catch,而是測試函數是否存在(還):

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

請注意,您無需明確說出

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

因為如果它們作為對象/函數存在,它們將被評估為“真實”。

(如果你確實使用了try / catch並且函數已經加載但是它有一些錯誤,那么它不會觸發catch並重復重新運行該函數嗎?)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM