Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Deferreds

 Deferreds

sporto

July 25, 2013
Tweet

More Decks by sporto

Other Decks in Programming

Transcript

  1. They can be aggregated var def1 = $.Deferred(); var def2

    = $.Deferred(); $.when(def1, def2).done(function(one, two){ //… do something with one and two; }); //… later def1.resolve(val); //… even later def2.resolve(val);
  2. var animDef = $.Deferred(); var musicDef = $.Deferred(); $.when(animDef, musicDef).done(function(){

    show(); }); //when the music is loaded musicDef.resolve(); //when the animation is loaded animDef.resolve();
  3. var animDef = $.Deferred(); var musicDef = $.Deferred(); //…later musicDef.resolve();

    //…even later $.when(animDef, musicDef).done(function(){ show(); }); //No problem, still triggers, you cannot do that with event listeners!
  4. Fail and reject var def = $.Deferred(); def .done(function(result){ //do

    something }) .fail(function(){ //fallback }); //…later, something bad happened def.reject();
  5. Promises Loader function load(){ def = $.Deferred(); return def.promise(); }

    //..later function onLoad(){ def.resolve(); } Caller promise = loader.load(); promise.done(function(){ ..something }); //Cannot resolve here: //promise.resolve() not possible
  6. Combine them to create bigger promises var promise1 = $.when(animDef,

    musDef); var promise2 = $.when(msgDef, bgDef); $.when(promise1, promise2).done(function(){ //… do something with anim, music message and background });