SyntaxError:意外的令牌功能-异步等待Node.js

我正在尝试将Node 6.2.1版与一些代码一起使用。计划将大多数面向超级回调的代码迁移到看起来更干净甚至性能更好的代码上。


我不知道为什么,当我尝试执行节点代码时,终端抛出错误。


helloz.js


(async function testingAsyncAwait() {

    await console.log("Print me!");

})();

日志


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

我想念什么?请给我一些启示。


更新1:


我尝试按照Quentin的建议使用Babel,但是,我仍然收到以下错误。


更新的代码-


require("babel-core/register");

require("babel-polyfill");


    (async function testingAsyncAwait() {

        await console.log("Print me!");

    })();

日志


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 | })();


Helenr
浏览 537回答 3
3回答

阿晨1998

早于7.6版的Node版本不支持异步功能。如果您使用的是旧版本,则需要将代码(例如,使用Babel)转换为Node可以理解的JS版本。就是说,当前(2018年)的Node.js LTS版本是8.x,因此,如果您使用的是较早版本,则应强烈考虑升级。

紫衣仙女

Node.JS当前不完全支持ES6,因此您可以使用asyncawait模块或使用Bable对其进行转换。安装npm install --save asyncawaithelloz.jsvar async = require('asyncawait/async');var await = require('asyncawait/await');(async (function testingAsyncAwait() {    await (console.log("Print me!"));}))();
打开App,查看更多内容
随时随地看视频慕课网APP