开发者问题收集

异步/等待 Vuex

2019-03-29
1918

我想在创建的钩子中调用一个操作,等到它完成,然后在同一个钩子中显示结果。这可能吗?

我尝试在操作中放入 async / await,但没有帮助。
这是 store 中带有 async 函数的 action 属性:

 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个回答

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

您需要等待操作调用,因为它是一个异步函数。

Promise 版本

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)
  })
}
Decade Moon
2019-03-29