In Angular, what's the conceptual difference between the error and catch functions for promises?

前端 未结 3 2264
星月不相逢
星月不相逢 2021-02-19 03:16

I finally got Angular promise error handling down but it was counter-intuitive to me. I expected errors to be handled by the failure callback but instead I had to use a catch. <

相关标签:
3条回答
  • 2021-02-19 03:24

    The second argument should be almost never be used literally in application code while also using the first. It is mostly about promise library interoperability between different implementations.

    You should always use .catch unless you specifically have some weird corner case where you need .then(succcess, fail).

    See The .then(success, fail) anti-pattern.

    Also Q library (The one angular $q is based on) has similar section in their readme

    0 讨论(0)
  • 2021-02-19 03:28

    By angularJS documentation for $q:

    Methods

    then(successCallback, errorCallback, notifyCallback) – regardless of when the promise was or will be resolved or rejected, then calls one of the success or error callbacks asynchronously as soon as the result is available.

    .....

    catch(errorCallback) – shorthand for promise.then(null, errorCallback)

    The two pieces of code you posted are identical.

    0 讨论(0)
  • 2021-02-19 03:49

    I think you're slightly misunderstanding how promises work.

    In your first code block there is only one promise object and it's SomeAsyncService.getData(). The errorCallback is not called here because that promise is resolved.

    In the second code block there are actually 2 promise objects you're working with. Note that .then() "returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback". So what's happening is you're catching the error from the second promise returned from SomeAsyncService.getData().then(...).

    0 讨论(0)
提交回复
热议问题