Search code examples
javascriptpromiseasync-awaites6-promise

Promise not returning error - returning Syntax error


I'm a JS student. I have a piece of code that's returning me an error.

const { promises } = require("fs");

 const compareToTen = function(testNumber) { 
     return new Promise((resolve, reject) => {  
         if (typeof testNumber !== "number") { 
             reject("Not a number"); 
        }
         
         
         setTimeout(() =>{
                if (testNumber > 10) { 
                    resolve(true); 
                } 
                else { 
                    resolve(false);
                }
                }, testNumber*100)
    })
} 

let timeStart = Date.now()
let result= await compareToTen(8)
console.log("time", Date.now() - timeStart)
console.log("result", result)


SyntaxError: await is only valid in async function This is returning Syntax error. Could you guys explain what I did wrong here?


Solution

  • If you need to use async at the top level it's generally easiest to just write a main function like:

    async function main() {
      // My code with await in it
    }
    
    // Call it
    main();