Coffeescript 被咖啡脚本弄糊涂了

Coffeescript 被咖啡脚本弄糊涂了,coffeescript,hubot,Coffeescript,Hubot,我是一个完全的新手,如果这是一个愚蠢的问题,我很抱歉 我在写胡伯特的剧本。我不明白我做错了什么。我需要一些帮助。我想从大联盟那里拿到分数 我有这个 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'

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

我在写胡伯特的剧本。我不明白我做错了什么。我需要一些帮助。我想从大联盟那里拿到分数

我有这个

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语句打印“Boston”,但robot打印“[Object Object]”,我如何让robot打印“Boston”。注意:我打算对一系列其他响应重复使用getData函数


感谢您的帮助。

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

它可能会返回一个承诺或类似的东西,或是一些倾听回应的东西

试试这个(我简化了一点作为咖啡脚本的介绍,我希望它仍然清晰):


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

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)

(1) 你确定
.get()(err,res,body)->
正确吗?您通常会将回调传递给
get
,而不是像您那样说
get()(回调函数)
?(2) CoffeeScript函数返回其最后一个表达式的值,这可能是
[Object Object]
的来源。@muistooshort但最后一个语句是team,与控制台日志相同。从hubot文档来看,这种语法是正确的。
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)