[英]Function doesn't wait for async/await on addListener?
Supposedly, the component needs to wait for notificationsMixin
to finish before it changes the route, but it doesn't:据说,该组件需要在更改路由之前等待
notificationsMixin
Mixin 完成,但它不需要:
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)
})
}
})
}
}
}
Component:成分:
this.notificationsMixin().then(async () => {
this.$router.push('/profile')
})
This function resolves immediately.此功能立即解决。
async notificationsMixin () {
this.$Plugins.PushNotifications.register()
this.$Plugins.PushNotifications.addListener('registration', async (token) => {
await this.API(token.value)
})
this.$Plugins.PushNotifications.addListener('registrationError', () => {
//
})
},
Try adding await
尝试添加
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
}
}
I'm not 100% familiar with this plugin you are using, so you may have to tweak the code a bit.
我不是 100% 熟悉你使用的这个插件,所以你可能需要稍微调整一下代码。 But this should give you an idea of what to do.
但这应该让您知道该怎么做。
As an extra tip, it's not great practice (IMO) to mix then
with await
.作为额外的提示,将
then
与await
混合并不是很好的做法(IMO)。 Pick one and stick with it.选择一个并坚持下去。
And you don't need async
here:并且您在这里不需要
async
:
this.notificationsMixin().then(async () => {
this.$router.push('/profile')
})
change to:改成:
this.notificationsMixin().then(() => {
this.$router.push('/profile')
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.