node.js - 无法在 Cloud9 上的节点上创建异步方法
问题描述
我正在移植一些我在浏览器中编写的代码,发现我似乎无法在 NodeJS 中创建异步方法
class Test{
async hello(){
return "hello";
}
}
(async function(){
let test = new Test();
let hello = await test.hello();
console.log(hello);
})();
当我执行这个时,我得到一个错误:
/home/ubuntu/workspace/test.js:2
async hello(){
^^^^^
SyntaxError: Unexpected identifier
at createScript (vm.js:56:10)
at Object.runInThisContext (vm.js:97:10)
at Module._compile (module.js:542:28)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Timeout.Module.runMain [as _onTimeout] (module.js:604:10)
at ontimeout (timers.js:386:14)
at tryOnTimeout (timers.js:250:5)
这在节点中是不可能的,还是我在这里没有什么不正确的?
我在跑步Node 8.x
解决方案
该代码中发生的错误如下:
let hello = await test.hello();
^^^^
SyntaxError: Unexpected identifier
发生这种情况是因为您在函数await
之外使用关键字。async
从文档:
await 运算符用于等待 Promise。它只能 在异步函数内部使用。
class Test{
async hello(){
return "hello";
}
}
(async() => {
// You can only use `await` inside async function
let test = new Test();
let hello = await test.hello();
console.log(hello);
})();
Is this just not possible in node, or am I don't something incorrect here?
I am running Node 8.x
Nodeasync/await
从 7.6 版本开始支持,所以你可以自由使用。
更新:
如果你得到:
async hello(){
^^^^^
SyntaxError: Unexpected identifier
这意味着您正在运行较旧的节点版本。尝试
console.log(process.version);
并且会 100% 打印低于 7.6 的版本。
您的 cli 上可能有节点 8.x,但 cloud9 上没有,要更新 cloud9 中的节点,请检查以下问题:
推荐阅读
- sql-server - 根据参数按 ASC 或 DESC 排序?
- perl - perl 跳过数组中的值
- c# - 一种将文件从一个云复制到另一个云的方法?
- notepad++ - 配置 Notepad++ 以将制表符转换为 * 精确 * 空格数
- github - 为什么“qa”部分没有显示“查看部署”按钮
- javascript - 推送功能在嵌套的 json 调用中不起作用(来自使用 jquery 的多个 API)
- dart - 推送后无法获得堆叠的小部件列表
- android - 当用户在 Android 中切换应用程序的“背景限制”时,是否有系统广播?
- python-3.x - 在 jupyter notebook 的 shell 中解释以下代码的工作
- php - 如何排除要在php中抓取的url