【问题标题】:Vuex store action from Promise to async/await从 Promise 到 async/await 的 Vuex 存储操作
【发布时间】:2019-11-02 04:40:01
【问题描述】:

目前我在商店操作中使用promises,但想将其转换为async/await。这是一个带有 promise 的 store 动作示例:

fetchActiveWorkspace (context, workspaceID) {
    if (workspaceID) {
      return this.$axios.get(`@api-v01/workspaces/workspace/${workspaceID}`)
        .then(response => {
          context.commit('setActiveWorkspace', response.data)
        })
        .catch(err => {
          throw err
        })
    } else {
      return Promise.resolve(true)
    }
  },

fetchActiveWorkspace 操作在组件中解析,因为它返回promise。如何将此代码 sn-p 转换为async/await 结构并在组件中使用?

【问题讨论】:

    标签: promise async-await action vuex store


    【解决方案1】:

    这就是我尝试翻译的方式;考虑到由于我无法访问完整上下文中的原始代码,因此我无法亲自尝试以确保它有效;但是,这仍然是您可以将 async/await 与 promise 一起使用的方式。

    // 1. Mark the function as `async` (otherwise you cannot use `await` inside of it)
    async fetchActiveWorkspace(context, workspaceID) {
        if (workspaceID) {
    
          // 2. Call the promise-returning function with `await` to wait for result before moving on.
          // Capture the response in a varible (it used to go as argument for `then`)
          let response = await this.$axios.get(`@api-v01/workspaces/workspace/${workspaceID}`);
          context.commit('setActiveWorkspace', response.data);
        }
    
        // 3. I don't think this is necessary, as actions are not meant to return values and instead should be for asynchronous mutations.
        else {
          return true;
        }
    }
    

    你可以用try/catch 包围函数体,以防你想捕获和处理异常。我没有添加它是为了简单起见,因为基于 Promise 的代码只会捕获并重新抛出异常,而不做任何其他事情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-26
      • 2019-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多