Użycie deferred

by Dominik Wilk

HTML

<div class="result">Status:<br></div>

JavaScript

$(function(){
  function asyncEvent() {
    var dfd = jQuery.Deferred();

    // Resolve after a random interval
    setTimeout(function() {
      dfd.resolve( "hurray" );
    }, Math.floor( 400 + Math.random() * 2000 ) );

    // Reject after a random interval
    setTimeout(function() {
      dfd.reject( "sorry" );
    }, Math.floor( 400 + Math.random() * 2000 ) );

    // Show a "working..." message every half-second
    setTimeout(function working() {
      if ( dfd.state() === "pending" ) {
        dfd.notify( "working... " );
        console.log('notify');
        setTimeout( working, 200 );
      }
    }, 1 );
    
    dfd.always(function(x){
    console.log(x);
    });

    // Return the Promise so caller can't change the Deferred
    return dfd.promise();
  }

  // Attach a done, fail, and progress handler for the asyncEvent
  $.when( asyncEvent() ).then(
    function( status ) {
      $( ".result" ).append( status );
    },
    function( status ) {
      $( ".result" ).append( status );
    },
    function( status ) {
      $( ".result" ).append( 123 );
    }
  );
});