NodeJS script with asynchronous / pending syntax error call (v7.10.0)

I am trying to use async / await in NodeJS, but my script is throwing a syntax error.

I got the impression that async / await is supported naively with Node 7.6 . When I run node -v , I get v7.10.0 .

Here is the contents of index.js :

 async function getValueAsync() { return new Promise(function(resolve) { resolve('foo'); }); } let value = await getValueAsync(); console.log(value); 

But when I call this script with node index.js , I get:

 let value = await getValueAsync(); ^^^^^^^^^^^^^ SyntaxError: Unexpected identifier at createScript (vm.js:53:10) at Object.runInThisContext (vm.js:95:10) at Module._compile (module.js:543:28) at Object.Module._extensions..js (module.js:580:10) at Module.load (module.js:488:32) at tryModuleLoad (module.js:447:12) at Function.Module._load (module.js:439:3) at Module.runMain (module.js:605:10) at run (bootstrap_node.js:427:7) at startup (bootstrap_node.js:151:9) 

I am running Linux Mint 18.1.

How can I compile and run my script?

+5
source share
1 answer

await only works inside async functions, so you need, for example, aync IIFE to wrap your code:

 void async function() { let value = await getValueAsync(); console.log(value); }(); 

And, since the return values ​​from the async functions are wrapped with a promise, you can shorten getValueAsync to a simple one:

 async function getValueAsync() { return 'foo'; } 

Or do not mark it as async and return a promise from it:

 function getValueAsync() { return new Promise(function(resolve) { resolve('foo'); }); } 
+7
source

Source: https://habr.com/ru/post/1268069/


All Articles