【问题标题】:calling 2 https requests simultaneously in hubot coffescript在hubot coffeescript中同时调用2个https请求
【发布时间】:2014-04-08 15:02:39
【问题描述】:
module.exports = (robot) ->
  robot.respond /log (.*)/i, (msg) ->
    group = "test"
    incident_message = msg.match[0]
    service_key = keys[group]
    curtime = new Date().getTime()
    incident_key = "hubot/#{curtime}"
    reporter = msg.message.user.name
    query = {
      "service_key": service_key,
      "incident_key": incident_key,
      "event_type": "trigger",
      "description": "Change Log #{reporter}",
      "details": "#{incident_message}"
    }
    string_query = JSON.stringify(query)
    content_length = string_query.length
    msg
      .http("https://events.pagerduty.com/generic/2010-04-15/create_event.json")
      .headers
      "Content-type": "application/json",
      "Content-length": content_length
      .post(string_query) (err, res, body) ->
      result = JSON.parse(body)
      if result.status == "success"
        msg.send "Your log has been sent"
      else
        msg.send "There was an error sending your log."
    msg
      .http("https://xyz.pagerduty.com/api/v1/incidents/#{incident_key}/acknowledge")

我正在尝试自动确认在 pagerduty 中触发的事件。第一个http请求生效。但是第二个 http 请求(代码的最后一行)永远不会生效。我尝试过 varipus 组合。但这无济于事。我是coffeescript的新手,只将它用于hubot。有人可以帮我吗?

【问题讨论】:

    标签: coffeescript hubot


    【解决方案1】:

    首先,您没有指定您正在执行的 HTTP 操作:

    msg.http("https://xyz.pagerduty.com/api/v1/incidents/#{incident_key}/acknowledge")
    

    应以.get().post() 结尾。

    另外,可能是因为粘贴不好,中间的缩进有点偏离:

      .post(string_query) (err, res, body) ->
      result = JSON.parse(body)
      if result.status == "success"
        msg.send "Your log has been sent"
      else
        msg.send "There was an error sending your log."
    

    应该是:

      .post(string_query) (err, res, body) ->
        result = JSON.parse(body)
        if result.status == "success"
          msg.send "Your log has been sent"
        else
          msg.send "There was an error sending your log."
    

    另外,由于 NodeJS 的特性,这些 HTTP 调用是异步进行的,第二次调用很有可能在第一次调用之前完成。为避免这种情况,请从第一个回调中运行第二个请求:

    msg
      .http("https://events.pagerduty.com/generic/2010-04-15/create_event.json")
      .headers
      "Content-type": "application/json",
      "Content-length": content_length
      .post(string_query) (err, res, body) ->
        result = JSON.parse(body)
        if result.status == "success"
          msg.send "Your log has been sent"
          msg
            .http("https://xyz.pagerduty.com/api/v1/incidents/#{incident_key}/acknowledge")
            .get()
        else
          msg.send "There was an error sending your log."
    

    您可以找到一些 Hubot HTTP 请求示例和其他脚本技巧here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-20
      • 2017-02-04
      • 1970-01-01
      • 2011-02-25
      • 2019-01-27
      • 1970-01-01
      相关资源
      最近更新 更多