Javascript VueJS-不能使用关键字';等待&x27;在异步函数之外
我有这段代码,我得到了一个错误-“不能在异步函数外使用关键字'await”: 我如何解决这个问题?我被困在这上面好几个小时了Javascript VueJS-不能使用关键字';等待&x27;在异步函数之外,javascript,vue.js,Javascript,Vue.js,我有这段代码,我得到了一个错误-“不能在异步函数外使用关键字'await”: 我如何解决这个问题?我被困在这上面好几个小时了 谢谢。您不需要自己用来打开承诺。然后,,因为您已经使用了异步函数。当您使用时((result)=>{…})该箭头函数不再是异步的。我的建议是: try { const result = await this.$validator.validateAll() if (result) { this.state = 'LOADING';
谢谢。您不需要自己用
来打开承诺。然后,
,因为您已经使用了异步函数。当您使用时((result)=>{…})
该箭头函数不再是异步的。我的建议是:
try {
const result = await this.$validator.validateAll()
if (result) {
this.state = 'LOADING';
this.response = [];
const authResponse = await axios.post('/api/auth/login', this.user);
const auth = authResponse.data;
if (auth.success) {
this.$authLoggedIn(auth);
this.$authRedirectToDefault();
} else {
this.response.push(auth.error);
this.state = 'ERROR';
}
}
} catch (error) {
this.state = 'ERROR';
this.response.push(error);
}
try {
let result = await this.$validator.validateAll();
if (result) {
this.state = 'LOADING';
this.response = [];
const authResponse = await axios.post('/api/auth/login', this.user);
const auth = authResponse.data;
if (auth.success) {
this.$authLoggedIn(auth);
this.$authRedirectToDefault();
} else {
this.response.push(auth.error);
this.state = 'ERROR';
}
}
} catch (error) {
this.state = 'ERROR';
this.response.push(error);
}```
或者,您可以通过执行以下操作将箭头函数标记为异步:
this.$validator.validateAll().then(async (result) => {
登录函数已经是异步函数,您可以使用wait.then()调用此.validator。因为inside.then(()=>{})是另一个回调函数,不是异步函数。 我的建议是:
try {
const result = await this.$validator.validateAll()
if (result) {
this.state = 'LOADING';
this.response = [];
const authResponse = await axios.post('/api/auth/login', this.user);
const auth = authResponse.data;
if (auth.success) {
this.$authLoggedIn(auth);
this.$authRedirectToDefault();
} else {
this.response.push(auth.error);
this.state = 'ERROR';
}
}
} catch (error) {
this.state = 'ERROR';
this.response.push(error);
}
try {
let result = await this.$validator.validateAll();
if (result) {
this.state = 'LOADING';
this.response = [];
const authResponse = await axios.post('/api/auth/login', this.user);
const auth = authResponse.data;
if (auth.success) {
this.$authLoggedIn(auth);
this.$authRedirectToDefault();
} else {
this.response.push(auth.error);
this.state = 'ERROR';
}
}
} catch (error) {
this.state = 'ERROR';
this.response.push(error);
}```
我们知道,
async..await
是pair关键字
只是在上面的函数中使用了async
。内部函数没有async关键字,但在函数中使用了wait
。这就是它显示错误的原因。只是我标记了一个非async
(result)/*this function has not async*/ => {
if (result) {
this.state = 'LOADING';
this.response = [];
const authResponse = await axios.post('/api/auth/login', this.user);
const auth = authResponse.data;
if (auth.success) {
this.$authLoggedIn(auth);
this.$authRedirectToDefault();
} else {
this.response.push(auth.error);
this.state = 'ERROR';
}
}
});
所以您必须在内部函数中使用async关键字
异步(结果)=>{/*您的代码在这里*/}