簡體   English   中英

函數不等待 addListener 上的 async/await?

[英]Function doesn't wait for async/await on addListener?

據說,該組件需要在更改路由之前等待notificationsMixin Mixin 完成,但它不需要:

混入:

export const notificationsMixin = {
  methods: {
    async notificationsMixin () {
      this.$Plugins.PushNotifications.register()

      this.$Plugins.PushNotifications.addListener('registration', async (token) => {
        await this.API(token.value)
      })

      this.$Plugins.PushNotifications.addListener('registrationError', () => {
        //
      })
    },
    async API (token) {
      await this.$axios.post('https://api.fexler.com/?action=notifications', token).then(async (response) => {
        if (response.data) {
          await this.$Plugins.Storage.set({
            key: 'token',
            value: JSON.stringify(token)
          })
        }
      })
    }
  }
}

成分:

this.notificationsMixin().then(async () => {
  this.$router.push('/profile')
})

此功能立即解決。

async notificationsMixin () {
      this.$Plugins.PushNotifications.register()

      this.$Plugins.PushNotifications.addListener('registration', async (token) => {
        await this.API(token.value)
      })

      this.$Plugins.PushNotifications.addListener('registrationError', () => {
        //
      })
    },

嘗試添加await

async notificationsMixin () {
    try {
        await this.$Plugins.PushNotifications.register()

        const token = await this.$Plugins.PushNotifications.addListener('registration')

        await this.API(token.value)

        this.$Plugins.PushNotifications.addListener('registrationError', () => {
            //
        })
    }
    catch (e) {
        // handle error
    }
}

我不是 100% 熟悉你使用的這個插件,所以你可能需要稍微調整一下代碼。 但這應該讓您知道該怎么做。

作為額外的提示,將thenawait混合並不是很好的做法(IMO)。 選擇一個並堅持下去。

並且您在這里不需要async

this.notificationsMixin().then(async () => {
  this.$router.push('/profile')
})

改成:

this.notificationsMixin().then(() => {
  this.$router.push('/profile')
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM