语法错误:意外的令牌异步()

时间:2017-09-04 04:45:19

标签: javascript node.js asynchronous

我一直关注使用GraphQL的this教程,它告诉我在我的src/index.js文件中编写这段代码:

const express = require('express');
const bodyParser = require('body-parser');
const {graphqlExpress, graphiqlExpress} = require('apollo-server-express');
const schema = require('./schema');

// 1
const connectMongo = require('./mongo-connector');

// 2
const start = async () => {
  // 3
  const mongo = await connectMongo();
  var app = express();
  app.use('/graphql', bodyParser.json(), graphqlExpress({
    context: {mongo}, // 4
    schema
  }));
  app.use('/graphiql', graphiqlExpress({
    endpointURL: '/graphql',
  }));

  const PORT = 3000;
  app.listen(PORT, () => {
    console.log(`Hackernews GraphQL server running on port ${PORT}.`)
  });
};

// 5
start();

虽然当我尝试使用node ./src/index.js运行代码时,它会给我这个错误:

const start = async () => {
                    ^

SyntaxError: Unexpected token (
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:542:28)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:389:7)
    at startup (bootstrap_node.js:149:9)

我在线搜索过,似乎可能是由here的node.js版本引起的,但我检查了我的noed.js版本,它是8.3.0所以应该支持如果我没弄错的话,不必使用巴别塔。

这是我的package.json文件:

{
  "name": "graphql-js-tutorial",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "apollo-server-express": "^1.1.2",
    "body-parser": "^1.17.2",
    "express": "^4.15.4",
    "graphql": "^0.11.2",
    "graphql-tools": "^1.2.2",
    "mongodb": "^2.2.31"
  }
}

2 个答案:

答案 0 :(得分:5)

async functions仅在节点8.3

之后可用

您的代码相当于(没有异步/等待)

const start = () => {
    return connectMongo().then(mongo => {
        var app = express();
        app.use('/graphql', bodyParser.json(), graphqlExpress({
            context: {mongo}, // 4
            schema
        }));
        app.use('/graphiql', graphiqlExpress({
            endpointURL: '/graphql',
        }));

        const PORT = 3000;
        app.listen(PORT, () => {
            console.log(`Hackernews GraphQL server running on port ${PORT}.`)
        });
        return;
    });
};

答案 1 :(得分:-1)

通过命令node yourAppFile -harmony启动您的应用! 在Node7。+

下的async模式下可以使用harmony功能