Mazzy Mazzy - 1 year ago 390
Javascript Question

SyntaxError: Unexpected token using async and babel in koa

I have this simple app made using the last alpha version of Koa. In order to use `async/wait Babel.Js is required.

'use strict';

// babel registration (runtime transpilation for node)

const Koa = require('koa');
const app = new Koa();

// define logger - this will be always executed
const logger = async (context, next) => {
const start = new Date;
await next();
const ms = new Date - start;
console.log(`${context.method} ${context.url} - ${ms}ms`);

const index = (context) => {
context.body = 'Hello World';


app.listen(3000);`The app is listening on port 3000`);

This is the hook to activate the transpiling.

const fs = require('fs');

let config;

try {
config = JSON.parse(fs.readFileSync('./.babelrc'));
} catch (error) {
console.error('==> ERROR: Error parsing your .babelrc.');


and this is the config file:

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

Unfortunately when I try to run the project I get the following error:

const logger = async (context, next) => {

SyntaxError: Unexpected token (
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:404:25)
at Object.Module._extensions..js (module.js:432:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:313:12)
at Function.Module.runMain (module.js:457:10)
at startup (node.js:138:18)
at node.js:974:3

I have no idea why I get this error. I'm using the last Node.Js version
and Babel

Answer Source

You are getting the SyntaxError. That happens because your code is being parsed before Babel can intercept it and convert.

If you want to make async functions work in your first file, you should require this entire file after have registered its hook.

Create a new file start.js with the following


Your code in index.js can use async functions, but you can't do it in the start.js.

Also note, that you don't need to read .babelrc by yourself. Babel will do it for you by default.

Contents of .babelrc looks like this

  "presets": [
  "plugins": [
        "polyfill": false,
        "regenerator": true

Reference links