通过检查响应来处理 promise 中的错误

Handling error in promise by checking the response

我需要处理以下示例代码中 '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)
);

首先你必须了解 Promise 是如何工作的。 then() 方法有两个功能。首先是成功,其次是失败。失败可以用es6中的.catch来写。现在首先了解 catch 仅在网络故障、500 错误、404 未找到错误时被调用。在这种情况下,没有要处理的数据。

但是您想要的是 200 Ok 但如果数据丢失。您已经将代码本身成功了:

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