首页 文章

在JavaScript Axios中嵌套API调用,返回正确的承诺

提问于
浏览
0

我正在尝试使用axios将数据发布到我的API . 我需要请求并发送XSFR令牌以及请求 . 我正在使用React,Redux,Thunk和Axios . 我需要将其作为React组件内部的承诺处理 . 它现在但它没有以所需的方式响应 . 只要令牌请求成功,它总是解析承诺,即使帖子失败也是如此 .

我在我的React组件中启动它的调用位于底部,即使axios调用在帖子上失败并且我确实从第二次调用的catch中获取了错误消息,它也给了我 . 如果我在其中放置Promise.reject(),它也会被发送但未被捕获,因为已经返回了一个promise,我想 .

我尝试在返回Promise.all([getToken()...]中包装整个事物 . 它工作但行为完全相同,仍然让我从接收令牌的成功和无视第二个axios调用的决心 .

操作:

export function Post(data) {

  return (dispatch) => {
    return getToken('csfr')
      .then(response => {
         return axios.post( '/post', {
           request: data,
           token: response,
           apitoken: 'apikey',
         })
         .then(response => {
           dispatch({type: 'POST', payload: response});
         })
         .catch(error => {
           dispatch(errorPopup({visible: true, message: error}));
           throw error;
         });

      })
      .catch(error => {
        dispatch(errorPopup({visible: true, message: error}));
      });

  };
}


export function getToken(tokentype) {
   return axios.post( '/token/' + tokentype, {
     apitoken: 'apikey',
   })
   .then()
   .catch(error => {
     throw error;
   });
}

React组件(使用Redux将post动作绑定到props):

componentWillMount() {
  this.props.Post(this.state.data)
  .then(() => {
    console.log('yes')
   })
   .catch(() => {
     console.log('no')
   });
 }

1 回答

  • 1

    如果您的目的是使用此Action Creator根据许多先前的异步请求的结果调度操作,则不应使用return关键字从异步操作返回Promise .

    删除内部 return 关键字并允许 .then.catch 分派您的操作 .

    相关地,我建议您调查Async / Await的使用 . 这段代码构造(以及解释难度)正是将Async / Await放入语言的原因 .

    以下代码(为满足您的架构而修改)将满足您的使用案例 . 请注意,我通过模拟方法等在各地获得了自由 . 例如,像 fetch()axios 方法返回一个承诺 . 我想你会得到主旨 . 如果您有任何疑问,请告诉我 .

    async function getToken(tokentype) {
      try {
        return await fetch('https://jsonplaceholder.typicode.com/posts/1')
      } catch (error) {
        throw error;
      };
    }
    
    function dispatch(data) {
      console.log(data);
    }
    
    
    
    function Post(data) {
      return async () => {
        try {
          let token = await getToken('csfr');
          let post = await fetch('https://jsonplaceholder.typicode.com/posts/1');
          dispatch({
            type: 'POST',
            payload: post
          });
        } catch (error) {
          dispatch('error: ' + error);
          throw error;
        };
      }
    }
    
    let attempt = Post('This is a test');
    attempt().then(() => {
      console.log('Completed Post');
    })
    

    小提琴:https://jsfiddle.net/0n6to6Lm/21/

    如果你想在React Editor中设置你的架构,我将很乐意帮助它成功 .

相关问题