0

The code is pretty straight foreword:

  var handleNextPressedDeferred = $.Deferred();
  $('input:button').live('click',function(){
    console.log('resolving');
    return handleNextPressedDeferred.resolve();
  });

  handleNextPressedDeferred.pipe(function(){
    console.log('rejecting');
    return $.Deferred().reject();
  });

  var handleNextPressedPromise = handleNextPressedDeferred.promise();

  handleNextPressedPromise.done(function(){
    console.log('done');
  });
  handleNextPressedPromise.then(function(){
    console.log('then');
  });
  handleNextPressedPromise.fail(function(){
    console.log('fail');
  });

After the original button click resolves the deferred, I'm interested in rejecting it by the piped function.

The expected outcome when the button is clicked is:

  • resolving
  • rejecting
  • fail

The actual outcome when the button is clicked is:

  • resolving
  • rejecting
  • done
  • then

What am I not understanding correctly here? I've tried a million variations of this and couldn't get it to work as expected.

1 Answers1

2

.pipe creates a new Deferred. In your code you are "connecting" .done, .then and .fail to the previous Deferred which is not rejected, that's why .done and .then are executed instead of .fail.

Try to replace this :

handleNextPressedDeferred.pipe(function(){
    console.log('rejecting');
    return $.Deferred().reject();
});

var handleNextPressedPromise = handleNextPressedDeferred.promise();

by

var handleNextPressedPromise = handleNextPressedDeferred.pipe(function(){
    console.log('rejecting');
    return $.Deferred().reject();
}).promise();

and it will work.

Fiddle here

Edit:

I see you are using both then and pipe in your code. I don't know which version of jQuery you are using, but be careful that since jQuery 1.8, pipe and then are strictly equivalent and return both a new Deferred. then is no longer syntactic sugar for .done and .fail.

See jQuery deferreds and promises - .then() vs .done() and pipe() and then() documentation vs reality in jQuery 1.8 for more information.

Community
  • 1
  • 1
Mordhak
  • 2,646
  • 2
  • 20
  • 14