0

Consider the following code:

var d1=$.Deferred();
var d2=$.Deferred();
d1.resolve();
d2.reject();
var p1=d1.promise();
var p2=d2.promise();
p1.then(function () {
    console.log('promiseOne resolved');
    return p2;
}).then(function () {
    console.log('promiseTwo resolved');
    }, function() {
    console.log('promiseTwo rejected'); });

where I am getting the results:

promiseOne resolved
promiseTwo rejected

My query is which promise do we have as caller object for the second .then method? To be more specific; if we had:

var x=p1.then(function () {
    console.log('promiseOne resolved');
    return p2;
})

it is that x!=p2 and that because .then returns a new jQuery.Deferred().promise() object. However, in which way p2 affects x? Does the new promise x gets only the value of p2.state()?

JJJ
  • 32,902
  • 20
  • 89
  • 102
Unknown developer
  • 5,414
  • 13
  • 52
  • 100
  • I think so, yes - as the onFulfilled function returns a promise, the state of `x` "adopts" the state of p2 - note, Promises in jQuery prior to 1.8 (i.e. what is used on this page) does **not** work that way, it's broken – Jaromanda X Feb 09 '16 at 11:12

1 Answers1

1

Yes, then does return a new promise (x) that resolves to the result of the callback - and if that result (p2) is a promise its state will get adopted so that x fulfills when p2 fulfills and rejects when p2 rejects. See also here and maybe read the Promises/A+ spec.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375