Hak*_*kim 4 javascript asynchronous es6-promise
有没有办法从 then 回调直接跳转到 JavaScript Promise“then-chain”内的 catch 回调?
因此,通过示例,我正在检查来自 fetch 调用的数据:
fetch('api')
  .then(response => {
      if (response.json() === null) {
         // error
         // call catch
      }
      else {
       return response.json();
      }
  })
  .then(data => console.log(data.message))
  .catch(error => console.log(error));
Run Code Online (Sandbox Code Playgroud)
有没有最佳实践或解决方法?
您可以调用Promise.reject该错误。您将在方法内收到错误catch()。
fetch('api')
    .then(response => {
        if (response.json() === null) {
            return Promise.reject('Somethind bad happened');
        }
        else {
            return response.json();
        }
    })
    .then(data => console.log(data.message))
    .catch(error => console.log(error));
Run Code Online (Sandbox Code Playgroud)
        |   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           2197 次  |  
        
|   最近记录:  |