兑现承诺的最佳方法是什么?为什么?

时间:2019-06-20 09:29:07

标签: javascript

我有两个代码示例来捕获Promise错误。有什么更好的方法,为什么呢?

我的代码带有.catch()

Message.receive($scope.reference).then(function (response) {
  // on success
}).catch(function (error) {
  // on error
});

我也有这段代码,没有.catch()

Message.receive($scope.reference).then(function (response) {
   // on success
}, function (error) {
   // on error
});

1 个答案:

答案 0 :(得分:1)

foo.then(success, error)根据foo是否引发错误来执行一个或另一个回调。如果success引发错误,除非链接另一个.catch,否则您将遇到未捕获的错误。

foo.then(success).catch(error)捕获到foo success 引发的任何错误。如果foo出现错误,则会跳过success

不是更好,这取决于要建立的错误处理链。