[javascript] SyntaxError: Unexpected token function - Async Await Nodejs

I was experimenting on using Node version 6.2.1 with some of my code. Had plans to migrate most of the hyper-callback oriented codes to something that looks cleaner and maybe performs better.

I have no clue why, the terminal throws up an error when I try to execute the node code.

helloz.js

(async function testingAsyncAwait() {
    await console.log("Print me!");
})();

Logs-

BOZZMOB-M-T0HZ:rest bozzmob$ node helloz.js 
/Users/bozzmob/Documents/work/nextgennms/rest/helloz.js:1
(function (exports, require, module, __filename, __dirname) { (async function testingAsyncAwait() {
                                                                     ^^^^^^^^
SyntaxError: Unexpected token function
    at Object.exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:513:28)
    at Object.Module._extensions..js (module.js:550:10)
    at Module.load (module.js:458:32)
    at tryModuleLoad (module.js:417:12)
    at Function.Module._load (module.js:409:3)
    at Function.Module.runMain (module.js:575:10)
    at startup (node.js:160:18)
    at node.js:456:3
BOZZMOB-M-T0HZ:rest bozzmob$ node -v
v6.2.1

What am I missing? Please throw me some light on the same.


Update 1:

I tried to use Babel as Quentin suggested, But, I am getting the following error still.

Updated Code-

require("babel-core/register");
require("babel-polyfill");

    (async function testingAsyncAwait() {
        await console.log("Print me!");
    })();

Logs-

BOZZMOB-M-T0HZ:rest bozzmob$ babel helloz.js > helloz.trans.js
SyntaxError: helloz.js: Unexpected token (3:7)
  1 | require("babel-polyfill");
  2 | 
> 3 | (async function testingAsyncAwait() {
    |        ^
  4 |     await console.log("Print me!");
  5 | })();

This question is related to javascript node.js express asynchronous async-await

The answer is


I too had the same problem.

I was running node v 6.2 alongside using purgecss within my gulpfile. Problem only occurred when I created a new Laravel project; up until that point, I never had an issue with purgecss.

Following @Quentin's statement - how node versions prior to 7.6 do not support async functions - I decided to update my node version to 9.11.2

This worked for me:

1-

$ npm install -g n

$ n 9.11.2

2-

delete 'node_modules' from the route directory

3-

$ npm install

Still not sure how node/purgecss worked prior to updating.. but this did the trick.


If you are just experimenting you can use babel-node command line tool to try out the new JavaScript features

  1. Install babel-cli into your project

    $ npm install --save-dev babel-cli

  2. Install the presets

    $ npm install --save-dev babel-preset-es2015 babel-preset-es2017

  3. Setup your babel presets

    Create .babelrc in the project root folder with the following contents:

    { "presets": ["es2015","es2017"] }

  4. Run your script with babel-node

    $ babel-node helloz.js

This is only for development and testing but that seems to be what you are doing. In the end you'll want to set up webpack (or something similar) to transpile all your code for production

If you want to run the code somewhere else, webpack can help and here is the simplest configuration I could work out:


Nodejs supports async/await from version 7.6.

Release post: https://v8project.blogspot.com.br/2016/10/v8-release-55.html


Though I'm coming in late, what worked for me was to install transform-async-generator and transform-runtime plugin like so:

npm i babel-plugin-transform-async-to-generator babel-plugin-transform-runtime --save-dev

the package.json would be like this:

"devDependencies": {
   "babel-plugin-transform-async-to-generator": "6.24.1",
   "babel-plugin-transform-runtime": "6.23.0"
}

create .babelrc file and write this:

{
  "plugins": ["transform-async-to-generator", 
["transform-runtime", {
      "polyfill": false,
      "regenerator": true
    }]
]
}

and then happy coding with async/await


include and specify the node engine version to the latest, say at this time I did add version 8.

{
  "name": "functions",
  "dependencies": {
    "firebase-admin": "~7.3.0",
    "firebase-functions": "^2.2.1",
  },
  "engines": {
    "node": "8"
  },
  "private": true
}

in the following file

package.json


Node.JS does not fully support ES6 currently, so you can either use asyncawait module or transpile it using Bable.

install

npm install --save asyncawait

helloz.js

var async = require('asyncawait/async');
var await = require('asyncawait/await');

(async (function testingAsyncAwait() {
    await (console.log("Print me!"));
}))();

node v6.6.0

If you just use in development. You can do this:

npm i babel-cli babel-plugin-transform-async-to-generator babel-polyfill --save-dev

the package.json would be like this:

"devDependencies": {
   "babel-cli": "^6.18.0",
   "babel-plugin-transform-async-to-generator": "^6.16.0",
   "babel-polyfill": "^6.20.0"
}

create .babelrc file and write this:

{
  "plugins": ["transform-async-to-generator"]
}

and then, run your async/await script like this:

./node_modules/.bin/babel-node script.js

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to express

UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block jwt check if token expired Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017] npm notice created a lockfile as package-lock.json. You should commit this file Make Axios send cookies in its requests automatically What does body-parser do with express? SyntaxError: Unexpected token function - Async Await Nodejs Route.get() requires callback functions but got a "object Undefined" How to redirect to another page in node.js

Examples related to asynchronous

How to read file with async/await properly? Use Async/Await with Axios in React.js Waiting until the task finishes How to reject in async/await syntax? React - Display loading screen while DOM is rendering? angular 2 how to return data from subscribe How do I access store state in React Redux? SyntaxError: Unexpected token function - Async Await Nodejs Why does .json() return a promise? Why is setState in reactjs Async instead of Sync?

Examples related to async-await

How to correctly write async method? How can I use async/await at the top level? Any difference between await Promise.all() and multiple await? Async/Await Class Constructor Syntax for async arrow function try/catch blocks with async/await Using filesystem in node.js with async / await Use async await with Array.map Using await outside of an async function SyntaxError: Unexpected token function - Async Await Nodejs