从hubot脚本中的嵌套匿名函数返回结果

时间:2015-09-04 00:08:15

标签: coffeescript hubot

以前从未使用过coffescript,我试图更新hubot script for jenkins integration。简而言之,我想调用jenkins,从该调用中获取结果并在后续调用中使用它。基于hubot脚本中的现有代码,我添加了以下功能:

jenkinsCrumb = (msg) ->
    url = process.env.HUBOT_JENKINS_URL
    path = "#{url}/crumbIssuer/api/json"

    req = msg.http(path)

    if process.env.HUBOT_JENKINS_AUTH
      auth = new Buffer(process.env.HUBOT_JENKINS_AUTH).toString('base64')
      req.headers Authorization: "Basic #{auth}"

    req.get() (err, res, body) ->
        if err
          msg.reply "Jenkins says: #{err}"
        else if 200 <= res.statusCode < 400 # Or, not an error code.
          msg.reply "#{body}"
          body
        else if 404 == res.statusCode
          msg.reply "Unable to fetch crumb from Jenkins..."
        else
          msg.reply "Jenkins says: Status #{res.statusCode} #{body}"

调用此函数时,我想要的值在变量body中报告。对msg.reply的调用会在hubot聊天窗口中正确显示该值。

我想做什么,但无法弄清楚,如何让此函数返回body的值?我已尝试显式返回req.get()的值,但似乎它返回了完整的请求对象。

1 个答案:

答案 0 :(得分:1)

您只需将bodyjenkinsCrumb = (msg, callback) -> url = process.env.HUBOT_JENKINS_URL path = "#{url}/crumbIssuer/api/json" req = msg.http(path) if process.env.HUBOT_JENKINS_AUTH auth = new Buffer(process.env.HUBOT_JENKINS_AUTH).toString('base64') req.headers Authorization: "Basic #{auth}" req.get() (err, res, body) -> if err msg.reply "Jenkins says: #{err}" else if 200 <= res.statusCode < 400 # Or, not an error code. msg.reply "#{body}" body else if 404 == res.statusCode msg.reply "Unable to fetch crumb from Jenkins..." else msg.reply "Jenkins says: Status #{res.statusCode} #{body}" # critical part callback(body) (因为CoffeeScript)添加到匿名函数的末尾即可:

routes.MapRoute(
 name: "Profile",
    url: "{username}",
    defaults: new { controller = "Account", action = "Profile" },
    constraints: new { username = "Vinoth" }
);