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?
async
/await
works exactly the same way in methods. By error it seems that you are usingawait
out of a functionasync
. In your example you are usingawait
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).– Andre
const result = await instance.method()
would not be async?– MarceloBoni
await
will 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.– Chance
Does this Answer your Question? How can I use javascript async/await?
– Chance