Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

.then() always returns a new promise. What happens to that promise?

promiseB = promiseA.then( [successHandler], [errorHandler] );

when

promiseA

is

// promiseA is fulfilled with 'hello' // promiseA is rejected with 'bad request'


fulfilled with rejected with
promiseA
.then( null, myFunc1, myFunc2 )
value reason promiseA
.then( myFunc1, null, myFunc2 )
.then() .then()
.then( console.log ); and and .then( null, console.log );
successHandler(data)
// result: console shows 'hello' errorHandler(reason) // result: console shows 'bad request'
// fulfill bubbled to success handler has no success has a has an has no error // rejection bubbled to error handler
handler success error handler
handler
handler handler

promiseB resolve(value); promiseB reject(reason);


which
FULFILLMENT BUBBLED REJECTION BUBBLED

returns returns throws


result promiseZ err

promiseB resolve(result); promiseB ← promiseZ promiseB reject(err);

P R O M I S E F O R R E S U LT A S S I M I L AT I O N ERROR CAUGHT

// output promise is for returned val // output promise “becomes” returned promise // output promise will be rejected with error

promiseForVal2 = promiseForVal1 promiseForMessages = promiseForUser promiseForVal2 = promiseForVal1


.then( function success (val1) { .then( function success (user) { .then( function success (val1) {
val2 = ++val1; // do some code to get a new promise // THROWN ERROR '404' trying to make val2
return val2; return promiseForMessages; return val2;
}); }); });

// same idea, shown in a direct chain: // same idea, shown in a direct chain: // same idea, shown in a direct chain:

promiseForVal1 promiseForUser promiseForVal1


.then( function success (val1) { .then( function success (user) { .then( function success (val1) {
// do some code to make val2 // do some code to get a new promise // THROWN ERROR '404' trying to make val2
return val2; return promiseForMessages; return val2;
}) }) })
.then( function success (val2) { .then( function success (messages) { .then( null, function failed (err) {
console.log( val2 ); console.log( messages ); console.log('Oops!', err);
}); }); });

© 2 0 1 4 G A B R I E L L E B E C • G L E B E C @ G M A I L . C O M • F U L L S TA C K A C A D E M Y

You might also like