1

看了这篇博客对promises的处理,我修改了失败的例子:

var myApp = angular.module('myApp',[]);

myApp.controller("MyCtrl", function ($q, $scope) {

    (function() {
        var deferred = $q.defer();
        var promise = deferred.promise;
        promise.then(function(result) {
            console.log("success pass 1 - " + result);
            return result;
        }, function(reason) {
            console.log("failure pass 1, reason:", reason);
            throw new Error("failed with: " + reason);
        }).
        then(function(result) {
            console.log("2nd success! result: ", result);
        }, function(reason) {
            console.log("2nd failure! reason: ", reason);
        });


        console.log("calling deferred.reject('bad luck')");
        deferred.reject("bad luck");

    })();

对于我的第一个失败函数,我注意到替换throwreturn会导致:

calling deferred.reject('bad luck') 
failure pass 1, reason: bad luck 
2nd success! result:  Error {stack: (...), message: "failed with: bad luck"}

结果,我替换returnthrow达到预期的failure -> failure结果。

calling deferred.reject('bad luck') 
failure pass 1, reason: bad luck 
Error: failed with: bad luck at ...app.js
2nd failure! reason: Error {stack: ... "failed with: bad luck"}

抛出的错误似乎没有被捕获。这是为什么?内部故障案例不应该捕捉到这个抛出的错误吗?

此外,在链式 Promise 中,只能通过抛出一个Error?

4

2 回答 2

1

$q这是一种在某种意义上非常不正统的设计选择。

由于库不会为您跟踪未处理的拒绝,因此做出了设计决定 s 和 s 被$q区别对待throwreject这是为了避免错误被吞没的情况:

JSNO.parse("{}"); // note the typo in JSON, in $q, since this is an error
                  // it always gets logged, even if you forgot a `.catch`.
                  // in Q this will get silently ignored unless you put a .done
                  // or a `catch` , bluebird will correctly track unhandled
                  // rejections for you so it's the best in both.

他们被抓住,被处理但仍然被记录下来。

$q中,使用了拒绝:

return $q.reject(new Error("failed with: " + reason));
于 2014-05-31T15:58:43.657 回答
0

你现在可能已经找到了。如果你想用失败链接承诺,只在链的末端提供失败处理程序。

    promise.then(function(result) {
        console.log("success pass 1 - " + result);
        return result;
    } /* don't handle failure here. Otherwise, a
         new promise (created by 'then') wraps the
         return value (normally undefined) in a new
         promise, and it immediately solves it 
         (means success) since the return value of
         your failure handler is not a promise.

         leave failure handler empty, 'then' will pass
         the original promise to next stage if the
         original promise fails. */
    ).
    then(function(result) {
        console.log("2nd success! result: ", result);
    }, function(reason) {

        /* both 1st and 2nd failure can be captured here */

        console.log("1st or 2nd failure! reason: ", reason);
    });
于 2015-09-29T23:38:07.570 回答