【问题标题】:What is the best way to use async / await inside Nuxt plugin?在 Nuxt 插件中使用 async / await 的最佳方式是什么?
【发布时间】:2021-07-07 01:22:08
【问题描述】:

我想在 nuxt 插件中使用 vuex 操作进行 api 调用。但是当我使用 await 关键字时,Nuxt 给了我一个错误说Parsing error: Unexpected reserved word 'await'. 那么,我如何在我的 Nuxt 插件中使用 promise?这是我的相关代码->

export default (context) => async({ store, route, redirect }) => {
  const address = store.state.location.selectedAddress
  const payload = {}

  if (!address) {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        payload.latitude = position.coords.latitude
        payload.longitude = position.coords.longitude
        const result = await store.dispatch('location/fetchLocation', payload)
        console.log(result)
        console.log(
          store.state.location.details && store.state.location.details.address
        )
      },
      (error) => {
        console.log(error.message)
      }
    )
  }
}

【问题讨论】:

  • @Bravo const result = await store.dispatch('location/fetchLocation', payload)。得到了答案。是的,“承诺” getCurrentPosition 解决了这个问题。
  • 是的,已转换。谢谢。
  • 是的,它正在返回承诺。这就是为什么使用 await 关键字。
  • 哦,对不起......我完全误读了整个问题:p
  • 没关系。谢谢,您的评论有助于获得解决方案。

标签: javascript nuxt.js vuex es6-promise nuxtjs


【解决方案1】:

将 navigator.geolocation 中的函数转换为 promise 解决了这个问题

export default ({ store, route, redirect }) => {
  const address = store.state.location.selectedAddress
  const payload = {}

  if (!address) {
    navigator.geolocation.getCurrentPosition(
      async (position) => {
        payload.latitude = position.coords.latitude
        payload.longitude = position.coords.longitude
        const result = await store.dispatch('location/fetchLocation', payload)
        console.log(result)
        console.log(
          store.state.location.details && store.state.location.details.address
        )
      },
      (error) => {
        console.log(error.message)
      }
    )
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-10
    • 1970-01-01
    • 2022-06-11
    • 1970-01-01
    • 2017-09-27
    • 2013-11-25
    • 1970-01-01
    相关资源
    最近更新 更多