How do I use async/await with Javascript classes?

Asked

Viewed 42 times

1

I created a class with a method async, however, when I instate this class and run the method, an error is generated in my console, follow the example code and error below:

JS

class MyClass{
  async method(){
    const x = await 10; // exemplo meramente ilustrativo
    return x
  }
}

const instance = new MyClass()

const result = await instance.method()

console.log(result)

Error:

const result = await instance.method()
               ^^^^^

SyntaxError: await is only valid in async function

Does async/await work any other way when it comes to an object’s methods? Or am I doing something wrong?

  • 3

    async/await works exactly the same way in methods. By error it seems that you are using await out of a function async. In your example you are using await in the global scope, which is obviously not possible (it may seem possible if you do it through your browser console, but that’s because the console treats this condition automatically for you, the same does not happen in a code you declared on the page).

  • 1

    const result = await instance.method() would not be async?

  • 2

    awaitwill only have resulted if the method where you are using it is a promise, otherwise it will have no effect at all. In the documentation of the await it’s well explained that.

  • 2

    Does this Answer your Question? How can I use javascript async/await?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.