johnny_mac
johnny_mac

Reputation: 1951

Should I call .catch on a nested promise?

I have been asked what promise my .catch handles and now I am curious if I am correct or not. I believe, in the following code, that if there is an error in the inner promise, that it will be caught by the .catch I have on the calling promise. The question I was asked has me doubting my understanding, and while I don't think I should have a nested catch, I am unsure what the alternative solution would be. I am using native promises in node FYI.

  promise1(param1)
    .then((status) => {
      if (status !== 200) {
        return 'Error!';
      }
      promise2(param1, param2)//param2 defined out of this scope
        .then((result) => {
          return 'Yay, result!';
        })
    })
    .catch((error) => {
      return JSON.stringify({'Caught Error': error});
    })

I had thought about simply doing something like this but promise2 takes a second param:

  promise1(param1)
    .then((status) => {
      if (status !== 200) {
        return 'Error!';
      }
      return param1;
    })
    .then(promise2)
    .catch((error) => {
      return JSON.stringify({'Caught Error': error});
    })

So, the question? Should promise2 have its own .catch or would an error here be caught by the promise1 .catch? What is a better way to handle this if I am wrong?

Upvotes: 2

Views: 1669

Answers (1)

Bergi
Bergi

Reputation: 664297

I believe, in the following code, that if there is an error in the inner promise, that it will be caught by the .catch I have on the calling promise.

No. The catch will only handle rejections of the promise on which it was invoked.

You can (and should) however have that promise resolve with the inner promise, and also reject with an error when the inner promise rejects, by returning the promise from the then callback.

promise1(param1).then(status => {
  if (status !== 200) {
    return 'Error!';
  }
  return promise2(param1, param2);
//^^^^^^
})
.then(result => { // you can unnest this now
  return 'Yay, result!';
})
.catch((error) => {
  return JSON.stringify({'Caught Error': error});
})

Upvotes: 1

Related Questions