使Redux thunk调用同步以刷新令牌



集成redux和thunk中间件。访问令牌到期时,将调用刷新令牌api,成功后,将再次调用由于令牌到期而未成功的第一个api。

正在调用并返回刷新令牌api,因为它是异步的。并且在刷新令牌成功的响应之前立即调用编辑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',
'Content-Type': '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
});
});
};
}

您必须在此处使用异步等待。。。

export function editClothDetails(data, id) {
return  async function(dispatch, getState) {      // -> see here
.catch((error) => {
if(error.message === "Invalid token") {
await dispatch(refreshToken());                 //--> see here
dispatch(editClothDetails(data, id)); 
}

// your other code

};
}
export async function refreshToken() {.  /// ---> see here
return async (dispatch, getState) => {
dispatch({ type: actions.REFRESH_TOKEN_REQUEST });
/// your other code
};
}

最新更新