javascript - 异步箭头函数的语法错误

标签 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>

最佳答案

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

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

关于javascript - 异步箭头函数的语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45685160/

相关文章:

javascript - 通过 Webpack Require Context 将查询参数传递给 Loader

reactjs - 可以更改外部组件中的对象(元素)吗?

php - REACT + PHP - 仅在 POST 请求中阻止了我的 CORS 策略

javascript - jQuery $.data ('n' )返回空白,但 $.attr ('data-n' )获取值

javascript - 将 d3.gantt 图表附加到选定的 div

javascript - node.js 使用 LIMIT 计算 MySQL 查询

node.js - 将流信息写入视频文件

javascript - Nodejs 模块导出 TypeError

javascript - 如何使用 TypeScript 根据另一个属性将 React 组件的两个属性设置为可选?

javascript - 如何构建具有连接数据库的拖放 Web 应用程序?