首页 文章

承诺链被拒绝但只有实施

提问于
浏览
0

我正在阅读有关承诺和获取的内容并且非常困惑 . 我从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 回答

  • 1

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

    拒绝或错误导致“执行”从成功“跳跃”到拒绝

    如果拒绝处理程序返回的值不是被拒绝的值,则“执行”将“跳转”到成功链

    注意:我最早接触到的承诺没有 .catch ...因为 .then 实际上接受了两个参数 onFullfilledonRejected - 如果其中任何一个不是 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);
    

    现在它 reject 链中没有任何东西直到最底层,因此,这是下一个被执行的代码

    注意 . 一些Promise库中的.catch只是以下内容

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

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

    因此,如果 status 返回 Promise.reject ,则只执行 catch 函数 .

相关问题