首页 > 解决方案 > Vuex - 调用异步函数

问题描述

我正在尝试使用 Vue 的异步操作来进行 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

任何帮助将非常感激!

谢谢 :)

标签: javascriptapivue.jsasync-awaitvuex

解决方案


用这个改变你的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) : '';
},

推荐阅读