2016-12-15 21 views
0

試圖調用兩個API的動作。當一個人完成後再打另一個,然後在最後一個傳遞給一個減速器。 看起來像我的getAttending被調用的同時發佈,而不是後發佈完成。我是個新手,認爲我可以一個接一個地打電話給他們。還原thunk調用兩個不同的API請求

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

回答

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

我會添加異步/等待你的配置。使閱讀/調試這些事情變得更容易。

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

是什麼postDeclined =>(id)=> async(dispatch)=>是異步的某種方法從await?或者只是包裝鏈方法的名稱。 –

+0

async關鍵字提供了一個返回承諾的函數。 await關鍵字使該行成爲同步調用,並且在承諾解決之前不會繼續。 https://github.com/tc39/ecmascript-asyncawait –

+0

啊確定感謝您的解釋。 –

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

或使用成分和譁衆取寵(我個人比較喜歡Ramda

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