gpt4 book ai didi

javascript - Angular promise 行为

转载 作者:行者123 更新时间:2023-11-30 16:42:28 25 4
gpt4 key购买 nike

<分区>

在阅读 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 回调,但似乎并非如此。请问有人可以解释这种行为吗?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com