Ожидание завершения действия отправки за пределами компонента - PullRequest
1 голос
/ 21 апреля 2020

У меня есть экран, из которого пользователь выбирает тип викторины, затем должны быть сгенерированы вопросы викторины, в магазине должна быть обновлена ​​currentGameInformation, а затем должен появиться новый экран.

Поскольку действия по отправке асинхронны c, иногда 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?

1 Ответ

0 голосов
/ 21 апреля 2020

Вам необходимо await ваш SetGameStatus вызов функции. Поскольку ваша StartTheGame функция помечена как asyn c, все, что вам нужно сделать, это:

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);
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...