簡體   English   中英

語法錯誤:意外的令牌async()

[英]Syntax Error: Unexpected Token async()

我一直在關注這個使用GraphQL教程,它告訴我寫的代碼塊在我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)

我已經在網上搜索過,看來這可能是由這里的node.js版本引起的,但是我檢查了noed.js版本,它是8.3.0因此如果我不使用Babel,應該支持它。沒看錯。

這是我的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"
  }
}

異步功能僅在節點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;
    });
};

通過命令node yourAppFile -harmony啟動您的應用程序! 在Node7下的harmony模式下,可以使用async功能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM