简体   繁体   English

异步箭头功能的语法错误

[英]Syntax error on async arrow function

I am following this example, but on this section of code... 我正在关注示例,但在此部分代码中...

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}`);
  }
};

I get the following error 我收到以下错误

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>

The function syntax seems correct. 函数语法似乎正确。 You may need to update node, as async support didn't arrive until early this year (edit: version 7.6 after googling). 您可能需要更新节点,因为async支持直到今年年初才出现(编辑:谷歌搜索后的7.6版)。

You can rewrite using promises or try the --harmony flag when running from the command line. 从命令行运行时,可以使用--harmony重写或尝试--harmony标志。

You need to upgrade to node 7.6 (or higher ) since the async keyword wasn't supported in earlier versions. 您需要升级到节点7.6 (或更高版本 ),因为早期版本中不支持async关键字。 As of right now, 6.11 is the LST version and 8.3 is the latest. 截至目前,LST版本是6.11,而最新版本是8.3。

should enclose function with parentheses () 应该用括号将函数括起来()

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}`);
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM