开发者

Wait for async loaded classes to finish (without callback)

What's the proper way to wait for classes loaded asynchronously before calling on them?

Note: I'm in a complicated situation where I can't use the async load callback.

Is this the best way to do it?

cal开发者_运维百科lClassFunction : function () {
  try {
    waitingOnThisClass.someFunction();
  } catch (e) {
    setTimeout("superClass.callClassFunction()",250);
  }
}

*jQuery ways are worth mentioning if there are any...


Well. if jQuery is allowed -jquery promise interface and jQuery.Deferred is just the thing:

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

Another example;

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.' );
   });


One change I would make is to get rid of the try/catch and instead test if the function exists (yet):

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

Note that you don't need to explicitly say

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

because if they exist as objects/functions they'll evaluate as "truthy".

(If you do use a try/catch and the function has loaded but has some error in it won't that trigger the catch and just rerun the function again repeatedly?)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜