4

Right now, I have a rejected promise chain:

dfd = $.Deferred();

dfd
    .then(function(){}, function(x) {
        return x + 1; // 2
    })
    .then(function(){}, function(x) {
        return x + 1; // 3
    })
    .then(function(){}, function(x) {
        log('reject ' + x); // 3
        return x + 1; // 4
    });

dfd.reject(1)

I wonder how can I resolve it(steer to success handler) down along the .then chain?

Thanks

Kuan
  • 11,149
  • 23
  • 93
  • 201

1 Answers1

4

By returning a resolved promise at any desired point:

dfd
    .then(function(){}, function(x) {
        return x + 1; // 2
    })
    .then(function(){}, function(x) {
        return $.Deferred().resolve(x + 1); // switch to success
    })
    .then(function(){}, function(x) {
        log('reject ' + x); // this will never happen now
    });

The relevant part of the docs is (emphasis mine)

These filter functions can return a new value to be passed along to the promise's .done() or .fail() callbacks, or they can return another observable object (Deferred, Promise, etc) which will pass its resolved / rejected status and values to the promise's callbacks.

Jon
  • 428,835
  • 81
  • 738
  • 806
  • 2
    It's maybe worth noting that a resolved jQuery promise can be generated with `$.when()` or `$.when(value)`, either of which can be returned from an error handler to send a promise chain down the success path. – Roamer-1888 Jan 24 '15 at 02:14
  • 1
    Note that starting with the next version of jQuery doing `return x + 1` would also work. – Benjamin Gruenbaum Jan 24 '15 at 14:28
  • @BenjaminGruenbaum: I didn't know that. Is there somewhere I can read more about it? – Jon Jan 24 '15 at 23:05
  • @Jon the most recent place I wrote about it with references is [in this answer](http://stackoverflow.com/questions/28088034/do-jquery-promises-conform-promises-a/28088881#28088881) but the jQuery issue tracker is a good place to read about it too. – Benjamin Gruenbaum Jan 24 '15 at 23:56