异步箭头函数的语法错误

时间:2017-08-15 01:10:49

标签: javascript node.js reactjs

我正在关注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>

3 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

应该用括号()

括起函数
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}`);
  }
});