[英]Node: trying to use `async function` throwing error
I only have: 我只有:
router.post('/register', async (req, res) => {
// planning to use await in here
});
But I'm getting this error. 但是我收到了这个错误。 I have tried googling if node supports await/async but I cannot seem to get any headway, I just keep finding native modules to implement it into node (Which could very well be the issue, but I'm really hoping its a syntax error and that node supports async/await natively)
我试过googling如果节点支持await / async但我似乎无法取得任何进展,我只是继续寻找原生模块将其实现到节点中(这很可能是问题,但我真的希望它的语法错误和该节点本机支持async / await)
router.post('/register', async (req, res) => {
^
SyntaxError: Unexpected token (
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:374:25)
at Object.Module._extensions..js (module.js:405:10)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Module.require (module.js:354:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (/app.js:13:15)
at Module._compile (module.js:398:26)
at Object.Module._extensions..js (module.js:405:10)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Module.require (module.js:354:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (/www:7:11)
at Module._compile (module.js:398:26)
Any information would be great thanks. 任何信息都会非常感谢。
One option you have here is babel , which will can transpile ES7 syntax like this into something node can run. 你这里有一个选择是巴贝尔 ,这将可以transpile ES7语法类似这样的到的东西节点都可以运行。 Since ES7 is still a work in progress you don't get async/await out of the box, but babel offers a transform ( https://babeljs.io/docs/plugins/transform-async-to-generator/ ) that you can include to make this work.
由于ES7仍然是一项正在进行中的工作,因此您无法获得异步/等待开箱即用,但是babel提供了一个变换( https://babeljs.io/docs/plugins/transform-async-to-generator/ )可以包括使这项工作。
Edit: babel has this included in their stage3 preset. 编辑: babel将其包含在他们的stage3预设中。 So once you npm install babel and the preset:
所以一旦你安装了babel和预设:
npm install babel-core babel-preset-stage-3
And install babel-cli globally so you can run babel-node in your shell 并在全局安装babel-cli,以便在shell中运行babel-node
npm install -g babel-cli
Create a .babelrc like this: 像这样创建一个.babelrc:
{
"presets": [
"stage-3"
]
}
And a test script like this: 像这样的测试脚本:
'use strict';
function bar() {
return Promise.resolve('banana');
}
async function foo() {
return await bar();
}
foo().then(console.log);
You can confirm it's working like so: 您可以确认它的工作原理如下:
▶ babel-node test.js
banana
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.