gpt4 book ai didi

javascript - Angular $http 服务的 `then` 方法采用 2 个参数(成功和错误回调)。既然有错误回调,那么使用 `catch` 有什么意义呢?

转载 作者:行者123 更新时间:2023-11-29 19:27:30 28 4
gpt4 key购买 nike

Angular $http 服务有一个 then 方法,它接受 2 个参数作为回调(一个用于成功,一个用于错误)。既然已经有一个错误回调,那么使用 catch 方法有什么意义呢?为什么要使用它?

这是一个then-catch 实现:

$http.get("url").then(
function(results) {
//do something w/results.data
}).catch(function(e){
// handle errors in processing or in error.
});

这是一个带有 2 个参数的 then 实现:

$http.get("url").then(
//success function
function(results) {
//do something w/results.data
},
//error function
function(err) {
//handle error
}
);

编辑:这里的问题不同于 New Dev 的问题正在提议。这里的问题专门针对 then 的失败回调与 catch,而 other question是关于 errorcatch 的。尽管如此,在另一个主题中有一个响应暗示了 then 的失败回调。我投票决定保持此开放状态以获得更好的响应,并帮助用户专门寻找“then 的失败回调与 catch”的问题。

最佳答案

两者的区别

promise.then(onSuccess, onError)

promise.then(onSuccess).catch(onError)

是在第一种情况下,onError 处理 promise 的异常/拒绝,而在第二种情况下 - onError 处理异常/拒绝原始 promise 和由 onSuccess 生成的 promise 。

这可能看起来并不多,但是当您链接 promise 时,区别就变得很重要。

Promises 可以被认为是 async 等价于 try/catch block - 这才是它们真正的优势所在。

考虑以下同步调用序列:

var result;
try {
var d1 = doSomething1();
var d2 = doSomething2(d1);
var d3 = doSomething3(d2);

result = d3;
}
catch(e){
// land here if any of the above throws an exception
result = "not set";
}

对于 doSomethingN 的 promises 和异步版本,以下是等价的:

var result;
doSomething1()
.then(doSomething2)
.then(doSomething3)

.then(function(d3){
result = d3;
})
.catch(function(){
// land here if anything above throws an exception or returns a rejection
result = "not set";
});

因此,任何 doSomethingN 中的异常或对 promise 的拒绝都会到达 catch 处理程序。

这就是 .then 的错误处理程序变得违反直觉的地方。所以,如果你有这样的事情:

var result;
doSomething1()
.then(doSomething2)
.then(doSomething3, errorHandler3)

.then(function(d3){
result = d3;
})
.catch(function() {
result = "not set";
});

然后调用 errorHandler3 来处理 doSomething2doSomething1 的错误(如果没有 errorHandler2).但不是 doSomething3。而且,事实上,它应该“处理”这个错误——比如,期望它应该返回一个有效的类似 d3 的结果,而不是 doSomething3 会返回。或者,或者“重新抛出”(使用 return $q.reject())。

同步等价物将是以下困惑(我希望我做对了):

var d2, d3;
try {
var d1 = doSomething1();
d2 = doSomething2(d1);
}
catch(e){
d3 = errorHandler3(e);
}

try {
if (!d3) d3 = doSomething3(d2);
}
catch (e){
d3 = "not set";
}
result = d3;

关于javascript - Angular $http 服务的 `then` 方法采用 2 个参数(成功和错误回调)。既然有错误回调,那么使用 `catch` 有什么意义呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29991941/

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