Javascript-异步等待不';我不能用条件句工作
我已经为此工作了几个小时,但对于异步/等待的工作方式,我仍然越来越困惑。现在我有这个代码:Javascript-异步等待不';我不能用条件句工作,javascript,asynchronous,vue.js,async-await,vuejs2,Javascript,Asynchronous,Vue.js,Async Await,Vuejs2,我已经为此工作了几个小时,但对于异步/等待的工作方式,我仍然越来越困惑。现在我有这个代码: created: function () { Event.$on('open-stage', (stage) => { this.$validator.validateAll().then(() => { const validateFields = async () => {
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;
});
},
}
已创建:函数(){
事件。$on('开放舞台',(舞台)=>{
这是.$validator.validateAll()。然后(()=>{
const validateFields=async()=>{
const uniqueEmail=等待此消息。checkIfUniqueEmail();
如果(UniqueMail){
console.log('uniqueEmail为true');//{
警告(“错误”);
事件。$emit('change-stage-denied');
返回true;
});
});
},
方法:{
checkIfUniqueEmail(){
如果(!this.player.email | |!this.player.email.length){
返回true;
}
这是.$http.post('playerExists'{
电子邮件:this.player.email
})。然后(响应=>{
if(response.data.exists){
toastr.error(Good');
事件。$emit('change-stage-denied');
返回false;
}
返回true;
}).catch(错误=>{
警告(“失败”);
事件。$emit('change-stage-denied');
返回false;
});
},
}
我的目标很简单-如果方法
checkIfUniqueEmail()
返回true,我想查看console.log并将发出change state
。问题是常量uniqueEmail
始终是未定义的。只有在函数checkIfUniqueEmail()响应之后,我才能这样做
是真的吗?我需要更改什么?我正在使用vue.js 2.1.10。您需要让您的方法返回承诺
checkIfUniqueEmail() {
if (!this.player.email || !this.player.email.length) {
return true;
}
return 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;
});
}
考虑这一点:
异步函数validateFields(){
var uniqueEmail=等待checkIfUniqueEmail();
如果(UniqueMail){
log('uniqueEmail为true');
}
}
函数checkIfUniqueEmail(){
返回新承诺(解决=>{
设置超时(()=>{
解决('johny@bravo.com');
}, 1000)
})
}
validateFields()
checkIfUniqueEmail
需要是一个async
函数才能与wait
一起使用。呃,你的checkIfUniqueEmail
方法不返回承诺-在内部返回然后
回调本身是不够的,你不需要让它async
-return兑现承诺就足够了。但是当你这样做的时候,你可能应该放开然后和抓住,并适当地使用wait
。