2017-03-26 138 views
0

有人可以解釋爲什麼第二個由then函數返回的承諾解決了嗎?它在Promises實現中看起來像Angular JS bug。根據文件here第二個承諾也應該被拒絕。當主要承諾被拒絕時,角度解決了由「然後」函數返回的承諾

// Code goes here 
 
var myMod = angular.module("myMod", []); 
 
myMod.controller('bodyCtrl', function($scope, $timeout, $q) { 
 
    var deferred = $q.defer(); 
 
    deferred.promise.then(function(d) { 
 
     console.log("success called"); 
 
     return d; 
 
    }, function(d) { 
 
     console.log("failure called"); 
 
     return d; 
 
    }) 
 
    .then(function(d) { 
 
     console.log("success called2"); 
 
     return d; 
 
    }, function(d) { 
 
     console.log("failure called2"); 
 
     return d; 
 
    }); 
 
    
 
    $timeout(function() { 
 
     deferred.reject(); 
 
    }, 2 * 1000); 
 
});
<!DOCTYPE html> 
 
<html ng-app="myMod"> 
 

 
    <head> 
 
    <script src="https://code.angularjs.org/1.5.8/angular.js"></script> 
 
    <link rel="stylesheet" href="style.css" /> 
 
    <script src="script.js"></script> 
 
    </head> 
 

 
    <body ng-controller="bodyCtrl"> 
 
    <h1>Hello Plunker!</h1> 
 
    </body> 
 

 
</html>

+0

相關http://stackoverflow.com/questions/18758058/angularjs-promise-rejection-chaining –

+0

@georgeawg ......或返回'$ q.reject ()' –

回答

1

由於@Nikolaj大壩拉森@georgeawg說,你的問題是,在你的errorCallback()你是不是拋出異常。請看下面的例子(PLUNKER)...

function bodyCtrl($timeout, $q){ 
    deferred.promise 
    .then(function(d) { //Promise 1 
     console.log("success called"); 
     return d; 
    }, function(e) { 
     console.log("failure called"); 
     throw e; //Throw instead return 
    }) 
    .then(function(d) { //Promise 2 
     console.log("success called2"); 
     return d; 
    }, function(e) { 
     console.log("failure called2"); 
     throw e; //Throw instead return 
    }); 

    $timeout(function() { 
     deferred.reject("Custom Rejected: " + new Date()); 
    }, 2000); 
} 
+0

同時檢查這篇文章,瞭解更好http://stackoverflow.com/questions/23559341/using-success-error-finally-catch-with-promises-in-angularjs –

1

這是由設計。它的出現是因爲通過提供帶有errorCallback的承諾,您實際上正在處理/解決/捕獲拒絕(就像您在try ... catch塊中捕獲異常一樣)。如果刪除第一個errorCallback函數,您應該在開發人員控制檯中看到failure called2,或者如果您在第一個回調中引發新的異常。