SyntaxError: await is only valid in async functions in Javascript

Dung Do Tien Aug 28 2022 41

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.
  • E

    Elias Toss Aug 28 2022

    You need to know that .then() method is not an asynchronous method. So you can't use await keyword here.

    Solution:

    Change 

     await initData();

    To

     (async () => {
        await initMetamask();
    })();  

    Your issue will be solved.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close