2

I'm not sure if I'm understanding a certain aspect of promises correctly and I couldn't find what I was looking for after a brief google/SO search.

Can a resolved promise returned to a rejected callback ever fire a resolved method later in the chain? Using jQuery deferreds (and it's deprecated pipe method) as an example:

x = $.Deferred();

x
  .then(null,function() {
     return $.Deferred().resolve();
  })
  .then(function() {
     console.log('resolved');
  },function() {
     console.log('rejected');
  });

The above code, logs rejected, I would've expected it to log resolved because the Deferred in the first error callback returns a resolved promise.

On the contrary, the same code using jQuery's deprecated pipe method logs, as I would've expected resolved.

x = $.Deferred();

x
  .pipe(null,function() {
    return $.Deferred().resolve();
  })
  .pipe(function() {
     console.log('resolved');
  },function() {
     console.log('rejected');
  });

Am I thinking about something wrong by trying to resolve a promise inside a rejected callback?

Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100
  • Are you missing an `x.reject()` call in your examples? – Bergi Jul 09 '15 at 20:09
  • What version of jQuery are you using?! Since ages `x.then === x.pipe` and they act the same! – Bergi Jul 09 '15 at 20:11
  • possible duplciate of [When should I use jQuery deferred's “then” method and when should I use the “pipe” method?](http://stackoverflow.com/q/9583783/1048572) – Bergi Jul 09 '15 at 20:13

1 Answers1

1

For anybody who has run into this same thought process, the following page helped me out: https://gist.github.com/domenic/3889970

Specifically:

...you can feed the return value of one function straight into another, and keep doing this indefinitely. More importantly, if at any point that process fails, one function in the composition chain can throw an exception, which then bypasses all further compositional layers until it comes into the hands of someone who can handle it with a catch.

It seems jQuery's pipe method was a violation of the Promise's specification.

Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100
  • 2
    It is a violation, and they're fixing it in 3.0 beta. See stackoverflow.com/questions/23744612/problems-inherent-to-jquery-deferred for more details. – Benjamin Gruenbaum Jul 09 '15 at 14:22