【问题标题】:Syntax error on async arrow function异步箭头函数的语法错误
【发布时间】:2017-08-15 01:10:48
【问题描述】:

我正在关注this 示例,但是在这部分代码中...

const getApiAndEmit = async socket => {
  try {
    const res = await axios.get(
      "https://api.darksky.net/forecast/PUT_YOUR_API_KEY_HERE/43.7695,11.2558"
    ); // Getting the data from DarkSky
    socket.emit("FromAPI", res.data.currently.temperature); // Emitting a new message. It will be consumed by the client
  } catch (error) {
    console.error(`Error: ${error.code}`);
  }
};

我收到以下错误

D:\Documents\js\socketio-server\app.js:42
const getApiAndEmit = async socket => {
                        ^^^^^^
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 Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:389:7)
    at startup (bootstrap_node.js:149:9)
PS D:\Documents\js\socketio-server>

【问题讨论】:

  • 你安装的是什么版本的node?​​span>
  • PS D:\Documents\js\socketio-server> 节点 -v v6.11.0 PS D:\Documents\js\socketio-server>
  • 很明显,您的节点版本不支持async。您需要更新到节点 >= 7.6
  • 我认为他们直到 7.6 才支持 async/await。如果你可以升级,试试吧,一切都会好的。
  • 感谢升级工作

标签: javascript node.js reactjs


【解决方案1】:

应该用括号将函数括起来()

const getApiAndEmit = async (socket => {
  try {
    const res = await axios.get(
      "https://api.darksky.net/forecast/PUT_YOUR_API_KEY_HERE/43.7695,11.2558"
    ); // Getting the data from DarkSky
    socket.emit("FromAPI", res.data.currently.temperature); // Emitting a new message. It will be consumed by the client
  } catch (error) {
    console.error(`Error: ${error.code}`);
  }
});

【讨论】:

    【解决方案2】:

    函数语法似乎正确。您可能需要更新节点,因为 async 支持直到今年年初才到达(编辑:谷歌搜索后的版本 7.6)。

    在命令行运行时,您可以使用 Promise 重写或尝试--harmony 标志。

    【讨论】:

    • 请更新您的答案以包括他们需要支持的节点版本async
    【解决方案3】:

    您需要升级到节点7.6(或higher),因为早期版本不支持async 关键字。目前,6.11 是 LST 版本,8.3 是最新版本。

    【讨论】:

      猜你喜欢
      • 2017-08-15
      • 1970-01-01
      • 2018-06-15
      • 1970-01-01
      • 2019-08-07
      • 1970-01-01
      • 2016-06-03
      • 2017-12-13
      • 1970-01-01
      相关资源
      最近更新 更多