简体   繁体   中英

handling resolved/rejected Angular promises

Are these two ways of handling resolved/rejected Angular promises equivalent?

Exhibit A

promise.then(function (value) {
  console.log('promise resolved with val', value);
  return 'resolved';
})
.catch(function (reason) {
  console.log('promise rejected with reason', reason);
  return 'rejected';              
})

Exhibit B

promise.then(function (value) {
  console.log('promise resolved with val', value);
  return 'resolved';

}, function (reason) {
  console.log('promise rejected with reason', reason);
  return 'rejected';
});

The reason for my doubt is because I read that then returns a new promise, so it seems that A is functionally identical to

var anotherPromise = promise.then(function (value) {
  console.log('promise resolved with val', value);
  return 'resolved';
});

anotherPromise.catch(function (reason) {
  console.log('promise rejected with reason', reason);
  return 'rejected';              
})

which doesn't look the same as B, because catch is handling rejection of anotherPromise rather than promise .

Promises uses method chaining to return the same instance of the promise so even if it looks like you are creating a new version of the promise in the version where you are setting..

var anotherPromise = promise.then(function (value) {

..both promise and anotherPromise points to the same object.

Same thing applies to:

var a = {};
var b = a;
a.monkey = 'banana';
console.log(b.monkey); // 'banana'

They're functionally equivalent, and both will return a promise.

In the example with 2 callbacks, the second callback will handle the error, but since you're still calling .then , you'll still get a promise.

Meaning, you could even technically do something weird like this if you wanted to:

promise.then(function (value) {
  console.log('promise resolved with val', value);
  return 'resolved';

}, function (reason) {
  console.log('promise rejected with reason', reason);
  return 'rejected';
})
.then(function(eitherValue) {
  console.log('eitherValue will be either "rejected" or "resolved"');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM