问题描述
将redux与thunk中间件集成在一起。访问令牌到期时,将调用刷新令牌api,并在刷新令牌api成功时再次调用由于令牌过期而失败的第一个api。
由于刷新令牌api是异步的,因此正在调用它并返回。并且在刷新令牌成功响应之前立即调用edit api。我如何使其同步以便仅在收到刷新令牌的响应后才调用api
export function editClothDetails(data,id) {
return function(dispatch,getState) {
dispatch({ type: actions.EDIT_CLOTH_REQUEST });
fetch(BASE_URL + EDIT_CLOTH_URL + `/${id}`,{
method: "PUT",headers: {
'Accept': 'application/json','Content-Type': 'application/json','Authorization': 'Bearer ' + getState().Auth.accessToken
},body: JSON.stringify({ ...data })
})
.then(result => checkHttpStatus(result))
.then(result => checkForError(result))
.then(jsonResponse => {
dispatch({
type: actions.EDIT_CLOTH_SUCCESS,payload: jsonResponse
});
})
.catch((error) => {
if(error.message === "Invalid token") {
//what should be the right way to make these dispatches synchronous
dispatch(refreshToken());
dispatch(editClothDetails(data,id)); //setTimeout(()=> dispatch(editClothDetails(data,id)),100);
}
console.error("There is an error in editing cloth details !! " + error.message);
dispatch({
type: actions.EDIT_CLOTH_FAILED,payload: error.message
});
});
};
}
export function refreshToken() {
return (dispatch,getState) => {
dispatch({ type: actions.REFRESH_TOKEN_REQUEST });
fetch(BASE_URL + '/token',{
method: "GET",headers: {
'Accept': 'application/json','authorization': 'Bearer ' + getState().Auth.refreshToken
},})
.then(result => checkHttpStatus(result))
.then(result => checkForError(result))
.then(jsonResponse => {
storeLocally(constants.APP_NAME,jsonResponse);
dispatch({
type: actions.REFRESH_TOKEN_REQUEST_SUCCESS,payload: jsonResponse
});
})
.catch((err) => {
console.error("There is an error refreshing token !!" + err.message);
dispatch({
type: actions.REFRESH_TOKEN_REQUEST_FAILED,payload: err.message
});
});
};
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)