我是 javascript 新手,并且自学了 Promise API(异步操作)。但我对 then 方法中的结果处理有点困惑,特别是对于拒绝。
以下 2 个示例等效吗? (我只需要一个解释)
exp1:
promise.then(
(result) => {
console.log(result);
},
(error) => {
console.log(error);
}
);
exp2
promise.then(
(result) => {
if (result.ok) {
console.log(result);
} else {
console.log('error');
});
对于exp1,则使用了2个参数(结果和错误),对于exp2,只有一个参数,但它正在考虑同一块中的成功和失败结果,这在我看来是已实现的
大概您正在查看特定的承诺 - 打算使用具有
ok
键的对象来解决的承诺。例如,这就是 fetch()
的作用。
差异:
第一个代码不会检查此
ok
键的值,因此如果承诺履行时 result.ok
等于 false
,则输出将会不同。在这种情况下(当 ok
为 false 时)第一个代码片段将记录 result
对象(我们将看到 ok
是 false
),第二个代码片段将记录“错误”。
第二个代码不处理拒绝,因此如果 Promise 被拒绝,第一个代码将输出“错误”,而第二个代码将引发“未捕获(在承诺中)TypeError”。
请注意,
ok
在其响应中提供的 fetch
键表示它收到了 HTTP 响应,而拒绝则意味着存在更根本的错误。
如果你想在
ok
键是 false
的情况下执行 catch 处理程序,那么链式 Promise 如下:
fetch("https://httpstat.us/405").then(response => {
if (!response.ok) { // Throwing an error will reject the chained promise:
throw new TypeError("The 'ok' key is false, and 'status' is " + response.status);
}
console.log(response);
}).catch(error => {
console.log("############### OOPS ######################");
console.log(error);
});