我正在阅读有关承诺和获取的内容并且非常困惑 . 我从Introduction to fetch获得了以下代码 .
我的问题是:如果 status
返回被拒绝的 promise
会怎样? then(json)
在 then(status)
之后被链接,这是否意味着 then(json)
将不会执行任何操作,因为 then(json)
仅在 status
返回已解决的承诺时才会执行?或者这是否意味着如果状态返回被拒绝的承诺直到它到达底部的 catch
,并且 catch
捕获错误,那么链只是继续传递所有 then
?
或者,如果我错了,这段代码的正确解释是什么?
function status(response) {
if (response.status >= 200 && response.status < 300) {
return Promise.resolve(response)
} else {
return Promise.reject(new Error(response.statusText))
}
}
function json(response) {
return response.json()
}
fetch('users.json')
.then(status)
.then(json)
.then(function(data) {
console.log('Request succeeded with JSON response', data);
}).catch(function(error) {
console.log('Request failed', error);
});
2 回答
在我试图理解承诺的早期,我认为.then链是两条链......成功和拒绝
拒绝或错误导致“执行”从成功“跳跃”到拒绝
如果拒绝处理程序返回的值不是被拒绝的值,则“执行”将“跳转”到成功链
注意:我最早接触到的承诺没有
.catch
...因为.then
实际上接受了两个参数onFullfilled
和onRejected
- 如果其中任何一个不是function
它被忽略 -因此,您的代码可以编写如下:
现在它
reject
链中没有任何东西直到最底层,因此,这是下一个被执行的代码当一个promise被拒绝时,它直接进入
.catch()
而不执行链中的任何其他东西 .因此,如果
status
返回Promise.reject
,则只执行catch
函数 .