0

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?

Roamer-1888
  • 19,138
  • 5
  • 33
  • 44
Kajiyama VK
  • 336
  • 1
  • 3
  • 11
  • 2
    you can only `await` inside an `async` function. `let result= await compareToTen(8)` isn't in an async function. Use `.then()` instead – Liam Sep 17 '20 at 13:55
  • Also [use `;`](https://stackoverflow.com/questions/444080/do-you-recommend-using-semicolons-after-every-statement-in-javascript) all the time, not just some of the time – Liam Sep 17 '20 at 13:56
  • Try to define functions as functions, not as `const` variables. Here this could be `function compareToTen(...)` instead. That style you're using leads to a lot of confusion and complexity that's generally unnecessary, excepting a few very narrow cases where it's required. – tadman Sep 17 '20 at 21:56

1 Answers1

2

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();
tadman
  • 208,517
  • 23
  • 234
  • 262