【问题标题】:Why does Promises.all doesn't work in my vuex store为什么 Promises.all 在我的 vuex 商店中不起作用
【发布时间】:2020-05-25 13:46:39
【问题描述】:

我现在面临一个奇怪的问题。我的 vue 项目中有一个 vuex 商店,它被分隔在不同的模块中。我想用Promise.all()一次执行两个独立的异步vuex动作来享受first fail behavior的优势。

商店/模块/类别:

    async CATEGORIES({ rootState }) {
        const response = await axios.post('link_to_api', {
            // some arguments for the api
            arg: rootState.args
        })

        return response
    }

商店/模块/运输:

    async TRANSPORTATION({ rootState }) {
         const response = await axios.post('link_to_api', {
            // some arguments for the api
            arg: rootState.args
        })

        return response
    }

我知道想在Promise.all 中调用这些异步函数:

商店/模块/类别:

    async PUT_CATEGORIES({ commit, dispatch, rootState }) {
      try {
         const [resCategories, resTransportation] = await Promise.all([
            dispatch('CATEGORIES').catch(err => { console.log('Fehler bei Kabinenabfrage!'); throw {error: err, origin: 'kabine'}; }),
            dispatch('transportation/TRANSPORTATION', {root:true}).catch(err => { console.log('Fehler bei Flugabfrage!'); throw {error: err, origin: 'flug'}; })
        ]) 
         //do something after both promises resolved

      } catch(error) {
            // do something if one promise rejected
            commit('errorlog/ERROR', 4, {root:true})
            dispatch("errorlog/LOG_ERROR", {'origin': '2', 'error_code': '113', 'message': error.toString()}, {root:true})
            router.push({path: '/Error'})
        }  

我收到以下错误:

这很奇怪,因为我在 dispatch 中使用了 {root:true} 和前缀 transport 来访问 store 中传输模块的操作。这对于我在 catch 块中使用的 errorlog 模块中的 LOG_ERROR 操作非常有效。

如果我在类别模块中复制 TRANSPORTATION 操作,效果会很好...

以前有没有人遇到过这个问题并有过建议??

提前致谢!

【问题讨论】:

  • await.catch 以及try/catch 混合使用很奇怪
  • dispatch 是否返回一个 Promise?还是按照错误提示返回undefinedcannot read property 'catch' of undefined
  • 错误与Promise.all无关
  • 它应该返回一个承诺,但它似乎没有连接到其他模块中的 TRANSPORT 操作,因此它是undefined@Jaromanda X跨度>
  • 在某些情况下返回 Promise 而不是其他情况,这很奇怪

标签: javascript vue.js vuex es6-promise vuex-modules


【解决方案1】:

在您的情况下,{root:true} 作为第二个参数传递,尽管它应该作为第三个参数传递。

- dispatch('transportation/TRANSPORTATION', {root:true})
+ dispatch('transportation/TRANSPORTATION', null, {root:true})

根据vuex's doc

要在全局命名空间中调度操作或提交变更,请将 { root: true } 作为第三个参数传递给调度和提交。

他们还提供了示例代码(此处进一步简化)

modules: {
  foo: {
    namespaced: true,
    actions: {
      // dispatch and commit are also localized for this module
      // they will accept `root` option for the root dispatch/commit
      someAction ({ dispatch, commit, getters, rootGetters }) {
        dispatch('someOtherAction') // -> 'foo/someOtherAction'
        dispatch('someOtherAction', null, { root: true }) // -> 'someOtherAction'

【讨论】:

    猜你喜欢
    • 2012-11-07
    • 2017-05-14
    • 2020-01-01
    • 1970-01-01
    • 2019-02-17
    • 2020-02-10
    • 2019-11-09
    • 1970-01-01
    • 2020-10-13
    相关资源
    最近更新 更多