Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'await Unexpected identifier' on Node.js 7.5

I am experimenting with the await keyword in Node.js. I have this test script:

"use strict"; function x() {   return new Promise(function(resolve, reject) {     setTimeout(function() {       resolve({a:42});     },100);   }); } await x(); 

But when I run it in node I get

await x();       ^ SyntaxError: Unexpected identifier 

whether I run it with node or node --harmony-async-await or in the Node.js 'repl' on my Mac with Node.js 7.5 or Node.js 8 (nightly build).

Oddly, the same code works in the Runkit JavaScript notebook environment: https://runkit.com/glynnbird/58a2eb23aad2bb0014ea614b

What am I doing wrong?

like image 705
Glynn Bird Avatar asked Feb 14 '17 11:02

Glynn Bird


People also ask

Can I use async await in node JS?

Async functions are available natively in Node and are denoted by the async keyword in their declaration. They always return a promise, even if you don't explicitly write them to do so. Also, the await keyword is only available inside async functions at the moment – it cannot be used in the global scope.

What is await in node JS?

The await operator is used to wait for a Promise and get its fulfillment value. It can only be used inside an async function or at the top level of a module.

Is it good to use await in node JS?

Using async/await in Node. js syntax is preferable to the alternatives, which are stock promises or especially callbacks. It allows for much cleaner code which is easier to understand and maintain.

What is async await in Javascript?

An async function is a function declared with the async keyword, and the await keyword is permitted within it. The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.


1 Answers

Thanks to the other commenters and some other research await can only be used in an async function e.g.

async function x() {   var obj = await new Promise(function(resolve, reject) {     setTimeout(function() {       resolve({a:42});     },100);   });   return obj; } 

I could then use this function as a Promise e.g.

x().then(console.log) 

or in another async function.

Confusingly, the Node.js repl doesn't allow you to do

await x(); 

where as the RunKit notebook environment does.

like image 182
Glynn Bird Avatar answered Sep 28 '22 21:09

Glynn Bird