SyntaxError:意外的令牌函数 - Async Await Nodejs [英] SyntaxError: Unexpected token function - Async Await Nodejs
问题描述
我正在尝试将 Node 版本 6.2.1 与我的一些代码一起使用.曾计划将大部分面向超级回调的代码迁移到看起来更简洁且性能可能更好的代码.
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!");
})();
日志-
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.
更新 1:
我尝试按照 Quentin 的建议使用 Babel,但是,我仍然收到以下错误.
I tried to use Babel as Quentin suggested, But, I am getting the following error still.
更新代码-
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 | })();
推荐答案
异步函数 不支持由早于 7.6 版的 Node 版本.
您需要将您的代码(例如使用 Babel)转译为 Node 理解的 JS 版本,如果您正在使用旧版本.
You'll need to transpile your code (e.g. using Babel) to a version of JS that Node understands if you are using an older version.
也就是说,不支持异步函数的 Node.js 版本所有已过生命周期的结束并且不受支持,因此如果您使用的是早期版本,则应强烈考虑升级.
That said, versions of Node.js which don’t support async functions are now all past End Of Life and are unsupported, so if you are using an earlier version you should very strongly consider upgrading.
这篇关于SyntaxError:意外的令牌函数 - Async Await Nodejs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!