承诺 - 错误回调与捕获

时间:2015-09-23 16:41:36

标签: angularjs q angular-promise

在使用catch时,有人可以告诉我使用错误回调与$q.promise功能之间是否存在差异?

E.g。代码的两个代码段在功能上是等价的吗?

function doSomething0() {
    var deferred = $q.defer();

    ...

    return deferred.promise;
 }

 doSomething0()
    .then(doSomething1)
    .then(doSomething2)
    .then(doSomething3)
    .catch(function (err) {
        // do something with `err`
    });

VS

function doSomething0() {
    var deferred = $q.defer();

    ...

    return deferred.promise;
 }

 function errorHandler(err) {
    // do something with `err`
 }

 doSomething0()
    .then(doSomething1, errorHandler)
    .then(doSomething2, errorHandler)
    .then(doSomething3, errorHandler);

如果是这样,为什么要使用第二个呢?在我看来,它看起来更加丑陋并导致更多的代码重复?

2 个答案:

答案 0 :(得分:5)

两者都会达到同样的效果,除了第二个可以运行errorHandler三次(而不是一次)。你是正确的,它带来了一些代码重复,但它也允许你处理发生的任何错误,并继续你的链:

function errorHandler(err) {
  //log error, continue
  return $q.resolve('default value or something');
}

doSomething0()
  .then(doSomething1, errorHandler)
  .then(doSomething2, errorHandler)
  .then(doSomething3, errorHandler);

答案 1 :(得分:0)

让我们看一下第一个示例:

doSomething0()
    .then(doSomething1, errorHandler)
    .then(doSomething2, errorHandler)
    .then(doSomething3, errorHandler);


// I've represented functions invocations as if they were synchronous to simplify the example to focus on the error handling
// The above sample is in a way "equivalent" to
try {
    // doSomething0()
    try {
        // doSomething1()
        try {
          // doSomething2()
        } catch(e0) {
           // handle error
        }  
    } catch(e1) {
         // handle error
    }
} catch(e2) {
     // handle error
}
// doSomething3()

但是,如果doSomething3处理程序中发生异常,则不会对其进行处理。

好的,让我们看一下第二个示例:

doSomething0()
    .then(doSomething1)
    .then(doSomething2)
    .then(doSomething3)
    .catch(function (err) {
        // do something with `err`
    });


// I've represented functions invocations as if they were synchronous to simplify the example to focus on the error handling
// The above sample is in a way "equivalent" to
try {
    // doSomething0()
    // doSomething1()
    // doSomething2()
    // doSomething3()
}
catch(e) {
    // Catch 'em all
    console.log(e)
}