如何在成功调度其他操作后调用异步操作?
我正在学习Redux,我有一些关于异步操作的问题。(我正在使用thunk )
我有两个动作:
export const addToCart = addToCartData => dispatch => {
axios.post("/api/cart/add-to-cart", {addToCartData)
.then(res => {
dispatch({ type: ADD_TO_CART, payload: res.data });
})
.catch(err => console.log(err));
};
export const removeProduct = (userID) => dispatch => {
axios
.delete(`/api/wait-list/remove/${userID}`)
.then(res => {
dispatch({ type: REMOVE_FROM_WAITLIST, payload: res.data });
})
.catch(err => console.log(err));
};
我想在removeProduct
成功执行后才执行addToCart
操作!我试图用其中两个做第三个,它看起来像这样:
export const addToCartAndPemoveProduct = (data) => dispatch => {
dispatch(addToCart(data)
dispatch(removeProduct(data));
但它首先执行removeProduct
操作,然后执行addToCart
....
由于订单,我该如何做到正确?也许我应该从第一个承诺返回承诺并在成功解决之后执行第二个承诺?它看起来像这样:
export const addToCart = addToCartData => dispatch => {
return axios.post("/some", {addToCartData)
.then(res => { dispatch({ type: ADD.....})
};
export const addToCartAndPemoveProduct = (data) => dispatch => {
dispatch(addToCart({ userID, productId }))
.then(data => {
dispatch(removeProduct({ userID, productName, productDescr }));
})
}
可以吗?
答案 0 :(得分:0)
您总是想要在--port 80
之后发送removeProduct
吗?在这种情况下:
addToCart
可能会将操作重命名为export const addToCart = addToCartData => dispatch => {
// You'll have to get the userId here first, probably from getState() if it's not being passed in.
axios.post("/api/cart/add-to-cart", {addToCartData)
.then(res => {
dispatch({ type: ADD_TO_CART, payload: res.data });
dispatch(removeProduct(userId));
})
.catch(err => console.log(err));
};
以表达完整的交易。