Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get async functions to work in simple NodeJS script [duplicate]

So, NodeJS newbie here - please be gentle. ;)

The below code runs fine in a modern browser:

async function testAsync(){
    return await new Promise(function(resolve){
        setTimeout(function(){
            resolve('Hello World!');
        }, 1000)

    })
}

const test = await testAsync();
console.log(test);

It waits for 1000ms until printing "Hello World!" to the console, as expected.

Running Node 10.3.0 using the same code I get:

SyntaxError: await is only valid in async function

What am I missing?

Thanks!

like image 646
jBoive Avatar asked Sep 02 '26 05:09

jBoive


1 Answers

You can't await on the top level (yet) as you're trying to do with await testAsync();. Instead, use .then:

testAsync()
  .then(test => console.log(test));

Also, there isn't much point having an async function that returns an awaited Promise immediately; instead, just return the Promise:

function testAsync(){
  return new Promise(function(resolve){
    setTimeout(function(){
      resolve('Hello World!');
    }, 1000)
  });
}
testAsync()
  .then(test => console.log(test));
like image 71
CertainPerformance Avatar answered Sep 04 '26 20:09

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!