异步/等待Vuex

时间:2019-03-29 22:52:03

标签: asynchronous vue.js async-await vuex

我想在创建的挂钩中调用一个动作,等到完成后再在同一挂钩中显示结果。有可能吗?

我尝试将async / await置于操作中,但无济于事。
这是action中带有异步功能的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())
      })
    }
  }
})

1 个答案:

答案 0 :(得分:1)

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)
  })
}