【问题标题】:Confused by Coffeescript被 Coffeescript 搞糊涂了
【发布时间】:2016-04-29 03:12:24
【问题描述】:

我是个新手,如果这是一个愚蠢的问题,我很抱歉。

我正在编写一个 Hubot 脚本。我不明白我做错了什么。我需要一些帮助。我正在尝试从 MLB 获得分数。

我有这个……

module.exports = (robot) ->
  robot.hear /score/i, (msg) ->
    url = 'http://mlb.mlb.com/gdcross/components/game/mlb/year_2016/month_03/day_12/master_scoreboard.json'

    msg.send(getData(url))

  getData = (url) ->
    robot.http(url)
      .get() (err, res, body) ->
        result = JSON.parse(body)
        console.log(result.data.games.game[1].home_team_city)
        team = result.data.games.game[1].home_team_city

当我运行上述命令时,console.log 语句打印“波士顿”,但机器人打印“[对象对象]”我如何让机器人打印“波士顿”。注意:我打算将 getData 函数重新用于一堆其他响应。

感谢您的帮助。

【问题讨论】:

  • (1) 你确定.get() (err, res, body) -> 是对的吗?您通常不会将回调传递给get,而不是像您一样说get()(callback_function)吗? (2) CoffeeScript 函数返回它们最后一个表达式的值,这可能就是[Object Object] 的来源。
  • @muistooshort 但是最后一个语句是team,和控制台日志一样。从 hubot 文档来看,该语法是正确的。

标签: coffeescript hubot


【解决方案1】:

请求不返回结果,因为它是异步的。这意味着只有在服务器响应后才能获得结果。

它可能会返回一个 Promise 或类似的东西,或者是用来监听响应的东西。

试试这个(我精简了一下作为coffeescript介绍,希望还是清楚):

url = 'http://mlb.mlb.com/gdcross/components/game/mlb/year_2016/month_03/day_12/master_scoreboard.json'

module.exports = (robot) ->
  robot.hear /score/i, getData

getData = (msg) ->
  robot
    .http url
    .get() (err, res, body) ->
      team = JSON.parse(body).data.games.game[1].home_team_city
      console.log team
      msg.send team

【讨论】:

    【解决方案2】:

    你只需要使用回调......就像这样:

    module.exports = (robot) ->
    robot.hear /score/i, (msg) ->
    url = 'http://mlb.mlb.com/gdcross/components/game/mlb/year_2016/month_03/day_12/master_scoreboard.json'
    getData url, (cb) ->
      msg.send(cb)
    
    getData = (url, successCallback) ->
    robot.http(url)
      .get() (err, res, body) ->
        result = JSON.parse(body)
        console.log(result.data.games.game[1].home_team_city)
        team = result.data.games.game[1].home_team_city
        successCallback(team)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-31
      • 2015-12-28
      • 2017-01-16
      • 2022-01-23
      • 2019-01-12
      • 1970-01-01
      • 2014-08-14
      • 2016-02-16
      相关资源
      最近更新 更多