CNode

新手问个问题,为什么我写的async函数会报错呢??

问答
Hhopperhuang发布于9 年前最后回复9 年前6 回复13336 浏览0 收藏

代码如下: var fs = require('fs');

var readFile = function (fileName) { return new Promise(function (resolve, reject) { fs.readFile(fileName, function(error, data) { if (error) reject(error); resolve(data); }); }); }; var asyncReadFile = async function (){ var f1 = await readFile('./test.txt');

console.log(f1.toString());

};

我的node版本是 v7.1.0 执行命令的时候开了--harmony 报错: var asyncReadFile = async function (){ ^^^^^^^^ SyntaxError: Unexpected token function at Object.exports.runInThisContext (vm.js:78:16) at Module._compile (module.js:545:28) at Object.Module._extensions..js (module.js:582:10) at Module.load (module.js:490:32) at tryModuleLoad (module.js:449:12) at Function.Module._load (module.js:441:3) at Module.runMain (module.js:607:10) at run (bootstrap_node.js:420:7) at startup (bootstrap_node.js:139:9) at bootstrap_node.js:535:3

搞不懂为什么。 请有经验的大哥们帮我解决这个问题了,感激不尽。

查看回复

回复 (6)

H
hopperhuang#1·9 年前
引用 sjnho跟async没有关系,你上面那个函数readFile,括号和花括号多了。你对对看。。

@sjnho

async function t(){ await 123; } t().then(function(data){ console.log(data); })

报错: (function (exports, require, module, __filename, __dirname) { async function t(){ ^^^^^^^^ SyntaxError: Unexpected token function at Object.exports.runInThisContext (vm.js:78:16) at Module._compile (module.js:545:28) at Object.Module._extensions..js (module.js:582:10) at Module.load (module.js:490:32) at tryModuleLoad (module.js:449:12) at Function.Module._load (module.js:441:3) at Module.runMain (module.js:607:10) at run (bootstrap_node.js:420:7) at startup (bootstrap_node.js:139:9) at bootstrap_node.js:535:3

我的代码没有问题吧,为什么会报错呢。

已经是7.1.0的node了。

S
steambap#2·9 年前

不是--harmony吗?

E
Ende93#3·9 年前

用 node --harmony-async-await

F
feng-fu#4·9 年前

test来自vue-cnode

F
feng-fu#5·9 年前

test_again 来自vue-cnode

S
sjnho#6·9 年前

跟async没有关系,你上面那个函数readFile,括号和花括号多了。你对对看。。

参与回复
登录后即可参与回复。登录