-1

I have very simple code as below .

Function ls has async keyword and it returns Promise.

But , calling const val = await ls() gives below error.

SyntaxError: await is only valid in async functions and the top level bodies of modules

Can anybody pleasse help me why this error is coming as :

  1. The function ls has async keyword
  2. It also returns a Promise

Further more , using then clause like below , it works fine

ls().then(val => console.log(val)).catch(e => e)

But below code doesn't work

   async function ls() {
        return new Promise((resolve) => {
            resolve('Print Output !!')
        });
    }
    
    const val = await ls()
    console.log(val)
Atul
  • 1,560
  • 5
  • 30
  • 75
  • 2
    Error is self-descriptive that *SyntaxError: await is only valid in async functions and the top level bodies of modules* – DecPK Aug 26 '22 at 04:59
  • await must be inside an async function – sonEtLumiere Aug 26 '22 at 04:59
  • Is the code `await ls()` inside an async function or at the top level of a module? No, it's not. Therefore, it's not valid. Therefore, the code is not correct. Therefore the error message you saw was very precise and accurate in describing what the error is. – VLAZ Aug 26 '22 at 05:10

1 Answers1

2

async function ls() {
    return new Promise((resolve) => {
        resolve('Print Output !!')
    });
}

// Way 1
async function test() { //function created for "await ls()"
    const val = await ls(); //this await requires async
    console.log("Way 1 " + val)
}
test();

// Way 2
(async function() {
    const val = await ls();
    console.log("Way 2 " + val)
})();
Sakil
  • 666
  • 3
  • 8