Reputation: 733
I'm getting this error when I try to await outside the async function Can not use keyword 'await' outside an async function
and I wanted to know hich approach should I use to fix the issue? Thanks in advance.
Here is my code:
async addCoursToClassYear() {
setTimeout(() => {
this.loading = false;
await this.$store.dispatch("academicYear/addCoursToClassYear", {
...this.form,
...this.singleYear
})
.then(() => {
this.handleSuccess();
this.closeModal();
})
.catch(error => {
if (error.response.status === 422) {
this.serverValidation.setMessages(error.response.data.errors);
} else {
this.handleError(error);
}
});
})
},
Upvotes: 0
Views: 1087
Reputation: 358
You are using await inside setTimeout. So, you need to make async setTimeout function
async addCoursToClassYear() {
setTimeout(async() => {
this.loading = false;
await this.$store.dispatch("academicYear/addCoursToClassYear", {
...this.form,
...this.singleYear
})
.then(() => {
this.handleSuccess();
this.closeModal();
})
.catch(error => {
if (error.response.status === 422) {
this.serverValidation.setMessages(error.response.data.errors);
} else {
this.handleError(error);
}
});
})
},
I changed
setTimeout(() => {
To
setTimeout(async() => {
Upvotes: 2
Reputation: 907
Here, put async in just the function in which you using await.
async addCoursToClassYear() {
setTimeout(async () => {
this.loading = false;
await this.$store.dispatch("academicYear/addCoursToClassYear", {
...this.form,
...this.singleYear
})
.then(() => {
this.handleSuccess();
this.closeModal();
})
.catch(error => {
if (error.response.status === 422) {
this.serverValidation.setMessages(error.response.data.errors);
} else {
this.handleError(error);
}
});
})
},
Upvotes: 1