看了这篇博客对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");
})();
对于我的第一个失败函数,我注意到替换throw
为return
会导致:
calling deferred.reject('bad luck')
failure pass 1, reason: bad luck
2nd success! result: Error {stack: (...), message: "failed with: bad luck"}
结果,我替换return
为throw
达到预期的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
?