Vuex - Вызов Asyn c Функции - PullRequest
       15

Vuex - Вызов Asyn c Функции

0 голосов
/ 01 февраля 2020

Я пытаюсь использовать Vue Asyn c Actions для вызова API. Проблема в том, что данные возвращаются недостаточно быстро. Метод продолжается, не дожидаясь возвращения данных действия. При первом вызове this.lapNumber не определено. Вторая попытка работает как ожидалось.

Я вызываю действие с этим 'this.getRound (findRound);' в методе ниже

     getRaceInfo(date) {
      let showModal = false;
      let findRaceName = '';
      let findCircuitName = '';
      let findRound = '';
      let findLapNum = '';
      // iterate through each race to match date of current
      this.allRaces.forEach(el => {
        if (el.date != date) {
          return;
        } else {
          // if date match then give variables values
          findRaceName = el.raceName;
          findCircuitName = el.Circuit.circuitName;
          findRound = el.round;
          this.fetchRoundResults(findRound);
          console.log('after fetch');
          findLapNum = this.lapNumber;
          showModal = true;
        }
      });
      // assign the variables to corresponding data properties
      this.raceName = findRaceName;
      this.circuitName = findCircuitName;
      this.roundNum = findRound;
      this.lapNum = findLapNum;
      return showModal ? (this.isModalVisible = true) : '';
    },

Это вызванное действие:

  async fetchRoundResults({ commit }, roundNum) {
    try {
      const response = await axios.get(`http://ergast.com/api/f1/current/${roundNum}/results.json`);
      const roundInfo = response.data.MRData.RaceTable.Races[0];
      await commit('set_round_results', roundInfo);
      console.log('set result');
      return response;
    } catch (e) {
      console.log(e);
    }
  },
};

В консоли это то, что выполняется на основе журналов консоли:

after fetch

vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in v-on handler: "TypeError: Cannot read property '0' of undefined"

found in

---> <RaceCalendar> at src/components/Calendar.vue
       <App> at src/components/Dashboard.vue
         <App> at src/App.vue
           <Root>
warn @ vue.runtime.esm.js?2b0e:619
logError @ vue.runtime.esm.js?2b0e:1884
globalHandleError @ vue.runtime.esm.js?2b0e:1879
handleError @ vue.runtime.esm.js?2b0e:1839
invokeWithErrorHandling @ vue.runtime.esm.js?2b0e:1862
invoker @ vue.runtime.esm.js?2b0e:2179
original._wrapper @ vue.runtime.esm.js?2b0e:6911
vue.runtime.esm.js?2b0e:1888 TypeError: Cannot read property '0' of undefined
    at lapNumber (raceCalendar.js?8f5d:13)
    at wrappedGetter (vuex.esm.js?2f62:762)
    at Vue.eval (vuex.esm.js?2f62:95)
    at Watcher.get (vue.runtime.esm.js?2b0e:4473)
    at Watcher.evaluate (vue.runtime.esm.js?2b0e:4578)
    at Vue.computedGetter [as lapNumber] (vue.runtime.esm.js?2b0e:4830)
    at Object.get [as lapNumber] (vuex.esm.js?2f62:564)
    at VueComponent.mappedGetter (vuex.esm.js?2f62:900)
    at Watcher.get (vue.runtime.esm.js?2b0e:4473)
    at Watcher.evaluate (vue.runtime.esm.js?2b0e:4578)
set result

Если запустить снова, нет неопределенной ошибки, но все равно данные не «устанавливаются» до тех пор, пока метод не будет продолжен.

after fetch
set result

Любая помощь будет принята с благодарностью!

Спасибо:)

1 Ответ

1 голос
/ 01 февраля 2020

Измените getRaceInfo метод с этим

async getRaceInfo(date) {
  let showModal = false;
  let findRaceName = '';
  let findCircuitName = '';
  let findRound = '';
  let findLapNum = '';
  // iterate through each race to match date of current
  for await (let el of this.allRaces) {
    if (el.date != date) {
      return;
    } else {
      // if date match then give variables values
      findRaceName = el.raceName;
      findCircuitName = el.Circuit.circuitName;
      findRound = el.round;
      await this.$store.dispatch('fetchRoundResults',findRound)
      console.log('after fetch');
      findLapNum = this.lapNumber;
      showModal = true;
    }
  }
  // assign the variables to corresponding data properties
  this.raceName = findRaceName;
  this.circuitName = findCircuitName;
  this.roundNum = findRound;
  this.lapNum = findLapNum;
  return showModal ? (this.isModalVisible = true) : '';
},
...