【发布时间】:2018-06-22 01:10:55
【问题描述】:
我已经为此工作了几个小时,但我仍然对 async/await 的工作原理越来越感到困惑。现在我有这个代码:
created: function () {
Event.$on('open-stage', (stage) => {
this.$validator.validateAll().then(() => {
const validateFields = async () => {
const uniqueEmail = await this.checkIfUniqueEmail();
if(uniqueEmail) {
console.log('uniqueEmail is true'); // <-- this is what I need to achieve
Event.$emit('change-stage', this.wizardStage.successor);
}
};
validateFields();
}).catch(() => {
toastr.warning('Error');
Event.$emit('change-stage-denied');
return true;
});
});
},
methods: {
checkIfUniqueEmail() {
if (!this.player.email || !this.player.email.length) {
return true;
}
this.$http.post('playerExists', {
email: this.player.email
}).then(response => {
if (response.data.exists) {
toastr.error(Good');
Event.$emit('change-stage-denied');
return false;
}
return true;
}).catch(error => {
toastr.warning('Fail');
Event.$emit('change-stage-denied');
return false;
});
},
}
我的目标很简单 - 如果方法 checkIfUniqueEmail() 返回 true,我想查看 console.log 并将发出 change-state。问题是常量uniqueEmail 始终未定义。只有在函数checkIfUniqueEmail() 的响应为真后,我才能做到这一点?我需要改变什么?我正在使用 vue.js 2.1.10。
【问题讨论】:
-
checkIfUniqueEmail必须是async函数才能与await一起使用。 docs -
呃,你的
checkIfUniqueEmail方法没有return承诺 - 仅在then回调中返回是不够的
标签: javascript asynchronous vue.js async-await vuejs2