Vuex操作不等待完成axios承诺

时间:2020-01-29 21:53:46

标签: javascript vue.js axios vuex

我在Laravel + VueJS / Vuex堆栈中开发应用程序时遇到一种奇怪的情况。

我知道,如果未返回诺言,则调用它的父函数将不会等待其解析,因此事情将变得异步。通过http调用资源时,Axios默认情况下会返回一个Promise。

所以我有一个看起来像这样的父函数:

fetchInvoiceSeries() {
  var arr = []
  let invsrs = this.$store.getters['getInvoiceSeries']
  if (invsrs == null) {
    return this.$store
      .dispatch('get_invoice_series')
      .then(() => {
        invsrs = this.$store.getters['getInvoiceSeries']
        if (invsrs != null) {
          invsrs.forEach(function(s) {
            arr.push({
              value: s.id,
              text: s.series + ' / ' + s.increment
            })
          })
          this.series = arr
        } else {
          console.log('Error while fetching invoice series!')
        }
      })
      .catch(e => {
        console.log(e)
      })
  } else {
    invsrs.forEach(function(s) {
      arr.push({
        value: s.id,
        text: s.series + ' / ' + s.increment
      })
    })
    this.series = arr
  }
}

这是在vuex模块的action部分中定义的函数:

get_invoice_series({ commit }) {
    return get('/api/series/0')
        .then(response => {
            if (response.data && typeof response.data !== undefined) {
                let payload = response.data
                commit('SET_INVOICE_SERIES', payload)
            } else {
                console.log('error', error)
            }
        })
        .catch(error => {
            console.log('error', error)
        })
},

因此,如您所见,我从动作内部的axios返回get请求。在父级中,我要调用操作和“ then”关键字,以便在操作完成后进行一些处理。我也在使用箭头功能,因为我需要父功能中的上下文才能调用此。$ store ...

问题是,即使在检查getter以查看状态是否具有发票系列并使用get_invoice_series操作获取它们之后,我仍然没有在代码中判断该发票系列在内存中我写。控制台在获取发票系列时保持loggin'错误!' 我第一次执行代码和第二次执行(在信息处于状态后),代码将跳过获取发票系列(如预期)

你能告诉我我在做什么错吗?谢谢!

1 个答案:

答案 0 :(得分:1)

您的错误源于invsrs第一次为空,而第二次不为空。

这意味着您的函数get_invoice_series({ commit })是异步的,并且它返回一个promise。

为了提高可读性,也许您应该使用return表达式,独立于async/await语句进行调用:

async get_invoice_series({ commit }) {
    const response = await get('/api/series/0')
    if (response.data === undefined) return null    
    const payload = response.data
    commit('SET_INVOICE_SERIES', payload)
    return payload
},

然后让您的呼叫等待此提取处理:

async fetchInvoiceSeries() {
  let arr = []
  const invsrs = await this.$store.getters['getInvoiceSeries']
  // ...

这纯粹是猜测,请告诉我是否有帮助。