新手问个问题,为什么我写的async函数会报错呢??
发布于 7 年前 作者 hopperhuang 11888 次浏览 来自 问答

代码如下: 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 回复

跟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了。

不是–harmony吗?

用 node --harmony-async-await

回到顶部