0

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); } }); }) }, 
4
  • 2
    setTimeout(async () => { - That should fix it. Commented Jul 11, 2020 at 8:28
  • Why setTimeout without delay? It will place callback in event queue, yes, but if the callback is already asynchronous what is the point in delaying it's invocation by 4ms minimum? Commented Jul 11, 2020 at 8:41
  • @DrewReese, I forgot to add the delay. But the reason I have set up setTimout is because I want to have the submit button to load and be disabled for 2 seconds before submitting the request. To avoid double clicking by user. Commented Jul 11, 2020 at 9:36
  • 1
    i think you can just remove await in front of the dispatch. it looks no reason to use async/await in the function. Commented Jul 11, 2020 at 9:39

2 Answers 2

2

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() => {

Sign up to request clarification or add additional context in comments.

Comments

1

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); } }); }) }, 

1 Comment

remember there's a side-effect, I hope you already know the side-effects of async, the promise resolving thing. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.