Javascript 通过检查响应处理承诺中的错误

Javascript 通过检查响应处理承诺中的错误,javascript,reactjs,promise,response,Javascript,Reactjs,Promise,Response,我需要处理一个错误,其中响应不适合下面示例代码中的“then” getData().then(response => transformData(response)); 我可能需要这样做。但是,我对如何在“then”中获得“response”感到困惑 getData().then(response => transformData(response)).catch(() => if(!response.data) { dispatch({ type: 'some_action

我需要处理一个错误,其中响应不适合下面示例代码中的“then”

getData().then(response => transformData(response));
我可能需要这样做。但是,我对如何在“then”中获得“response”感到困惑

getData().then(response => transformData(response)).catch(() => if(!response.data) { dispatch({ type: 'some_action' });
}
如何访问“then”外部和catch内部的响应以分派另一个操作?

then()函数可以有两个参数。第一个是您正在使用的成功回调。第二个是失败回调,这是您想要的

getData().then(
  success => transformData(success),
  failure => doSomething(failure)
);

首先,你必须明白承诺是如何起作用的。那么()方法有两个函数。第一个是成功,第二个是失败。可以使用es6中的.catch写入故障。现在首先要了解catch只在网络故障、500错误、404未找到错误时被调用。在这种情况下,没有数据要处理

但你想要的是200,但如果数据丢失。您已将代码放入成功本身:

getData().then(response => {
  const res = transformData(response);
  if(!res.data) {
     // do your stuff
  }
   return res; // else normal behaviour
});

我认为您可以处理响应是否成功,但它没有I上的数据,或者如果请求刚刚出错,catch语句可以处理它:

getData()
  .then(response =>{
    if(!response.data) { 
     dispatch({ type: 'some_action_for_the_error', payload: response.error });
    } 
    else {
     transformData(response)
    }
  ).catch(( error ) =>{
    console.error(error);
    dispatch({ type: 'some_action_for_the_error', payload: error });
  }

您的意思是您只想捕获
transformData
步骤中的错误?请澄清您的问题。目前,您得到了三个不同的答案,因为我们只能猜测您需要什么。OP可能需要一个
if
/
else
而不是对无效响应运行
transformData
。是的,我想我错过了else语句