我有一个屏幕,用户可以从中选择一种类型的测验,然后生成测验问题,在商店中更新currentGameInformation,然后可以看到新的屏幕。
由于调度操作是异步的,有时currentGameInformation不会更新,所以我的应用程序在进入下一页时会崩溃。我想让它等到下一页,这样信息就可用了。
按下按钮后,我的组件中会调用一个名为startTheGame((的函数
//inside the screen component
startTheGame = async (id) => {
let navigation = this.props.navigation;
await StartTheGame(MASTER_TIME_PERIOD, {time_period_id: id}).then(function(){
console.log("Navigating");
navigation.replace('Quiz');
});
};
//This function is located outside the component,
//It is a library that handles all the Quiz functionalities
export async function StartTheGame(type, details) {
let state = store.getState();
let username = state.currentUser.username;
if(username === undefined){
//AWS gets the current user working fine and waiting to be completed
let user = await GetCurrentUserAWS();
username = user.username;
}
//set game status to loading
let currentGameInfo = {};
let currentDayPoints = await GetCurrentDayPointsForUserDB(username);
//Redux Thunk function (is sent, but not waiting to get done)
SetCurrentDayPoints(currentDayPoints);
//redux thunk function (is set but not waiting for it to be done)
SetGameStatus(SET_GAME_START_LOADING, QUIZ_GAME_START_STATUS_LOADING);
//at this point, current day points are either updated/not and same with game status
let questions = await GenerateQuestions(type, details).catch(err => {
SetGameStatus(SET_GAME_START_ERROR, QUIZ_GAME_START_STATUS_ERROR); //same not waiting to be completed
});
currentGameInfo = {
questions: questions,
points: 0,
questionIndexesAnsweredCorrectly: [],
questionIndexesAnsweredIncorrectly: [],
shouldRestartBeEnabled: false,
currIndex:0,
questionsAnsweredInRow:0,
gameType:type
};
SetGameStatusSuccess(currentGameInfo); //same not waiting
return currentGameInfo; }
我的目标是只有在SetGameStatusSuccess完成后才能返回
export function SetGameStatusSuccess(currentGameInfo){
return (dispatch, getState) => {
dispatch({type: SET_GAME_START_SUCCESS, payload:{
gameStatus:QUIZ_GAME_START_STATUS_STARTED,
currentGameInformation:currentGameInfo
}});
}; }
export function SetGameStatus(gameStatus, quizStatus){
return (dispatch, getState) => {
dispatch({type: gameStatus, payload:{gameStatus:quizStatus}});
};}
我想知道是否有一种方法可以在不需要mapDispatchToProps函数的情况下做到这一点?
您需要await
您的SetGameStatus
函数调用。由于您的StartTheGame
函数被标记为async,所以您所需要做的就是:
let currentDayPoints = await GetCurrentDayPointsForUserDB(username);
SetCurrentDayPoints(currentDayPoints);
//add 'await' here
await SetGameStatus(SET_GAME_START_LOADING, QUIZ_GAME_START_STATUS_LOADING);
此处相同:
let questions = await GenerateQuestions(type, details).catch(asybc (err) => {
await SetGameStatus(SET_GAME_START_ERROR, QUIZ_GAME_START_STATUS_ERROR);
});