<分区>
在阅读 this article 后,我正在尝试比较两种在 Angular 中使用 promises 的方法。 .
所以我使用这段代码来比较是否使用 deferred。注:地址http://localhost:1337/error返回具有 http 500 状态的响应和作为错误数据的消息“错误”(这是预期的行为)。
.controller("HomeCtrl", function($q, $http) {
function doAsyncCallDeferred() {
var deferred = $q.defer();
$http.get("http://localhost:1337/error")
.catch(function(errorData) {
// error
deferred.reject(errorData.data);
});
return deferred.promise;
}
function doAsyncCall() {
return $http.get("http://localhost:1337/error")
.catch(function(errorData) {
// error
return errorData.data;
});
}
doAsyncCallDeferred()
.then(function (data) {
console.log("with deferred success");
console.log(data);
})
.catch(function(errorData) {
// data should be "error"
console.log("with deferred error");
console.log(errorData);
});
doAsyncCall()
.then(function (data) {
console.log("without deferred success");
console.log(data);
})
.catch(function(errorData) {
// data should be "error"
console.log("without deferred error");
console.log(errorData);
});
})
但我对结果感到困惑:
with deferred error
error
without deferred success
error
我假设这两种方法都会执行 catch 回调,但似乎并非如此。请问有人可以解释这种行为吗?