asynchronous - 异步/等待 Vuex
问题描述
我想在创建的钩子中调用一个动作,等到完成并在同一个钩子中显示结果。那可能吗?
我试图将 async / await 放在操作中,但没有帮助。
这是action
具有 async 功能的属性store
:
actions: {
async FETCH_USER({commit}) {
await firebase.firestore().collection('test').get().then(res => {
commit('FETCH_USER', res.docs[0].data())
})
}
}
created() {
this.FETCH_USER()
console.log(this.GET_USER)
},
methods: {
...mapActions([
'FETCH_USER'
]),
login() {
if(this.$refs.form.validate()) {
console.log('welcome')
}
}
},
computed: {
...mapGetters([
'GET_USER'
])
}
export default new Vuex.Store({
state: {
user: null
},
getters: {
GET_USER: state => state.user
},
mutations: {
FETCH_USER(state, user) {
state.user = user
}
},
actions: {
FETCH_USER({commit}) {
firebase.firestore().collection('test').get().then(res => {
commit('FETCH_USER', res.docs[0].data())
})
}
}
})
解决方案
async
/await
版本
async FETCH_USER({ commit }) {
const res = await firebase.firestore().collection('test').get()
const user = res.docs[0].data()
commit('FETCH_USER', user)
return user
}
async created() {
// The action returns the user out of convenience
const user = await this.FETCH_USER()
console.log(user)
// -- or --
// Access the user through the getter
await this.FETCH_USER()
console.log(this.GET_USER)
}
您需要等待操作调用,因为它是一个异步函数。
承诺版
FETCH_USER({ commit }) {
return firebase.firestore().collection('test').get().then(res => {
const user = res.docs[0].data()
commit('FETCH_USER', user)
return user
})
}
created() {
this.FETCH_USER().then(user => {
console.log(user)
})
// -- or --
this.FETCH_USER().then(() => {
console.log(this.GET_USER)
})
}
推荐阅读
- python - 自定义使用python中的排序函数按升序对列表进行排序
- c# - Windows 窗体应用程序中的自动化消耗大量内存
- python - Python,Selenium 查找元素只能通过 css?
- matlab - 用所需的每个数据绘制极化电场曲线(滞后)
- r - 使用 JM 在 R 中拟合关节模型
- angular - 页面在最小化或暂停后恢复时的角度事件
- kubernetes - 在不影响就绪检查的情况下快速重启 statefulset pod
- c# - C# - Process.Start()
- php - 如何在 PHP 中嵌套正则表达式?
- android - 获取用户朝向地球真北方向并在 android 中旋转谷歌地图上的方向箭头的最新方法是什么?