【问题标题】:Vuex action not waiting to finish axios promiseVuex 操作不等待完成 axios 承诺
【发布时间】:2020-05-15 11:40:14
【问题描述】:

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

我知道如果没有返回一个 Promise,调用它的父函数不会等待它解决,所以事情会异步进行。通过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 返回获取请求。在父级中,我调用动作和“then”关键字,以便在动作完成后进行一些处理。我也使用箭头函数,因为我需要父函数中的上下文才能调用 this.$store ...

问题是,即使在检查 getter 以查看状态是否有发票系列并使用 get_invoice_series 操作获取它们之后,从代码判断我仍然没有发票系列在内存中我写。控制台保持登录 'Error while fetching invoice series!' 我第一次执行代码和第二次(在信息存在状态后),代码跳过获取发票系列(如预期)

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

【问题讨论】:

  • 没有什么明显错误的。我建议使用更多控制台日志记录来检查各个部分相对于彼此运行的顺序。 get 是如何声明的? SET_INVOICE_SERIES 突变是什么样的?除了返回 state 属性之外,getInvoiceSeries getter 是否还有其他作用?
  • 这只是SET_INVOICE_SERIES突变状态下的一个集合。声明 get 以验证数组的长度是否大于 1,如果为真则返回数组。
  • 1.请发布 getter getInvoiceSeries 的代码。 2、state中对应属性的初始值是多少? 3.你是如何导入/声明函数get的?

标签: javascript vue.js axios vuex


【解决方案1】:

您的错误来自invsrs 第一次为空,第二次不为空。

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

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

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']
  // ...

这里纯属猜想,如果有帮助请告诉我。

【讨论】:

  • Rn 我正在检查您的建议,如果这是问题所在,我会回来将答案标记为正确。谢谢!
  • 它仍然无法正常工作。无论如何,getter 是同步的,因此它可能不需要您提到的 await 运算符,我猜您提到了使用 await 运算符的动作调度。无论如何感谢您的帮助,但我无法将您的问题标记为正确,因为它没有解决我的问题。
猜你喜欢
  • 2017-06-17
  • 2019-07-30
  • 2018-03-05
  • 2016-10-16
  • 2020-11-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多