【发布时间】:2020-03-08 14:25:18
【问题描述】:
我是 async 的新手,我在 vuex 中有一个获取用户信息的操作,我把它放在了 promise 中,我想在 axios 调用块中使用这个方法来等待登录,因为用户信息的数据对于我
我的问题是我不能在 then 块中使用 await 并且错误说错误说 await can only be use in async function
这个流程是正确的,正确的方法是什么?
store.js:
actions: {
loadUserInfo({commit}){
const headers = {
'Content-Type': 'application/json',
// 'Authorization': localStorage.getItem('access_token'),
'Accept': 'application/json'
}
return new Promise(function(resolve, reject) {
axios.get(process.env.VUE_APP_BASE_URL + process.env.VUE_APP_EDIT_INFO,{headers: headers})
.then(response => {
commit('authenticateUser');
commit('setUserInfo', response.data.result);
resolve();
})
.catch(error => {
console.log(error);
reject();
})
});
}
},
登录.vue:
async login () {
let self = this;
axios.post(process.env.VUE_APP_BASE_URL + process.env.VUE_APP_LOGIN,
this.loginInfo
).
then(function (response) {
await this.$store.dispatch('loadUserInfo').then((res)=>{
this.$emit('authenticateUser', true);
this.$emit('registeredIdentification', self.$store.getters.getUsername)
this.$router.push({ name: 'mainBox' })
});
localStorage.setItem('access_token', response.data.result.access_token)
localStorage.setItem('refresh_token', response.data.result.refresh_token)
})
.catch(function (error) {
// let statusCode = error.response.status;
console.log(error);
});
}
【问题讨论】:
标签: javascript vue.js ecmascript-6 axios