SyntaxError: await is only valid in async functions in Javascript
Dung Do Tien Aug 28 2022 295
Hello guys. I am a newbie in javascript, I want to create an async function and call API to get the status of data from the database. Here is my code:
const initData = async (id) => {
var status = await getStatus(id);
if(status == 1){
return;
}
if(status == 0){
parent.blockchain.enable().then(function () {
await initData(); // re-call to continue thread & got error here
});
}
// Continue do something here.
}
When status = 0
I got an exception Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules.
I removed await keyword, but it didn't work for me.
Anyone can help?
Have 1 answer(s) found.
- E0
Elias Toss Aug 28 2022
You need to know that
.then()
method is not an asynchronous method. So you can't useawait
keyword here.Solution:
Change
await initData();
To
(async () => { await initMetamask(); })();
Your issue will be solved.
* Type maximum 2000 characters.
* All comments have to wait approved before display.
* Please polite comment and respect questions and answers of others.