拒绝时的承诺链,但只有在那时才实施

promise chain when rejected but only have then implermented

我在阅读有关 promise 和 fetch 的内容时感到非常困惑。我从 Introduction to fetch.

得到了以下代码

我的问题是:如果 status returns 被拒绝 promise 会怎样? then(json) 链接在 then(status) 之后,这是否意味着 then(json) 不会执行任何操作,因为 then(json) 仅在 status 返回已解决的承诺时执行?或者这是否意味着如果状态 returns 拒绝承诺,链会一直传递所有 then 直到它到达底部到达 catch,并且 catch 捕获错误?

或者如果我错了,这段代码的正确解释是什么?

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);  
  });

当一个 promise 被拒绝时,它会直接进入 .catch() 而不会执行链中的任何其他内容。

所以如果 status returns a Promise.reject 只有 catch 函数会执行。

在我尝试理解 promises 的早期,我认为 .then 链是两条链......成功和拒绝

拒绝或错误导致从成功到拒绝"execution"到"jump"

如果拒绝处理程序 returns 一个未被拒绝的承诺值,"execution" 将 "jump" 到成功链

注意:我最早接触 promises 没有 .catch ... 因为 .then 实际上接受两个参数 onFullfilledonRejected - 如果其中一个不是a function 它被忽略了 -

所以,你的代码可以这样写:

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()  
}

function log(data) {
  console.log(data);
}

function handleError(error) {
  console.log('Request failed', error);
}

fetch('users.json')  
  .then(status,   null)  
  .then(json,     null)  
  .then(log,      null)
  .then(null,     handleError);

现在很清楚,如果函数统计信息出错,"on rejected" 链在 "effect" 中(我真的需要考虑更好的术语),[=17 中什么也没有=] 链到最底部,因此,这是下一个要执行的代码

Note .catch in some Promise libraries is simply the following

Promise.prototype.catch = function catch(onRejected) {
    return this.then(null, onRejected);
};