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!
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With