Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/406.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 承诺从“然后”内部调用“捕获”`_Javascript_Asynchronous_Es6 Promise - Fatal编程技术网

Javascript 承诺从“然后”内部调用“捕获”`

Javascript 承诺从“然后”内部调用“捕获”`,javascript,asynchronous,es6-promise,Javascript,Asynchronous,Es6 Promise,有没有一种方法可以从then回调直接跳转到JavaScript承诺“then chain”中的catch回调 因此,通过示例,我正在检查一个提取调用中的数据: fetch('api') .then(response => { if (response.json() === null) { // error // call catch } else { return response.json();

有没有一种方法可以从then回调直接跳转到JavaScript承诺“then chain”中的catch回调

因此,通过示例,我正在检查一个提取调用中的数据:

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

有什么最佳实践或解决方法吗?

您可以在第一个
中抛出一个错误。然后

promise.then(response => {
      if (response.json() === null) {
         // error
         // call catch
           throw new Error('error !');
      }
      else {
       return response.json();
      }
  })
  .then(data => console.log(data.message))
  .catch(error => console.log(error)); // error !

您可以调用带有错误的
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));

你不会“呼叫捕获”,你会抛出一个错误。你不会抛出一个异常,你会返回一个被拒绝的承诺。