redux thunk调用两个不同的api请求

时间:2016-12-15 06:17:23

标签: reactjs redux react-redux redux-thunk

试图在一个动作中调用两个api。当一个完成后调用另一个然后在最后一个调用另一个传递给减速器。 看起来我的getAttending在发布的同时被调用,而不是在发布完成之后。我是redux-thunk的新手,并且认为我可以在完成后一个接一个地调用它们。

   export function postDeclined(id){
        let post = axios.post(blaBla.com);
        let getAttending = axios.get(attending.com);
        return (dispatch) => {
            post.then(()=>{
                getAttending.then(({data})=>{
                    dispatch({
                        type: type.NOT_GOING,
                        payload: data.data
                    });
                });
            });
        }
    }

3 个答案:

答案 0 :(得分:1)

尝试执行这样的api调用:

 export function postDeclined(id){
        return (dispatch) => {
             axios.post(blaBla.com).then(()=>{
                 axios.get(attending.com).then(({data})=>{
                    dispatch({
                        type: type.NOT_GOING,
                        payload: data.data
                    });
                });
            });
        }
    }

当您“声明”调用时,您实际上正在调用API ...所以它正在执行异步...

答案 1 :(得分:1)

我将async / await添加到你的babel配置中。使阅读/调试这些事情变得更加容易。

export const postDeclined => (id) => async (dispatch) => {
  const post await axios.post(blaBla.com);
  const getAttending = await axios.get(attending.com);
  return dispatch({
    type: type.NOT_GOING,
    payload: getAttending.data
  });
};

答案 2 :(得分:0)

代码示例存在一个非常常见的问题。该函数同时执行两项操作:调用apis并调度操作。此外,请注意,您可以链接承诺,您不需要该中间回调:

 export const postDeclined = id =>
   axios.post(blaBla.com).then(axios.get(attending.com));

 export const notifyNotGoing = dispatch => promisedResult =>
   promisedResult.then(({data}) =>
     dispatch({
       type: type.NOT_GOING,
       payload: data.data
     })
   );

然后你可以这样调用你的函数:

notifyNotGoing(dispatch)(postDeclined(2))

或使用作文和currying(我个人更喜欢Ramda

const prog = compose(notifyNotGoing(dispatch), postDeclined)
prog(2)