Coffeescript async and scope

26 views Asked by At

I have an array of URLs that I'm fetching and processing, the keys of which I would like to be able to reference when the data returns. What is the preferred way to ensure that a value determined before an asynchronous HTTP call is carried into the closure to be performed when the data returns? In the following example, the calendar_name variable is (as expected) lost when the data from the HTTP call returns, and I need to be able to reference that value inside the closure:

cals = {
  "calendar one":"http://example.com/info/webcal/abc123.ics",
  "calendar two":"http://example.com/info/webcal/xyz789.ics"
}
for calendar_name,calendar_url of cals
  # Note that this is a Hubot script and the following line performs an HTTP call
  msg.http(calendar_url)
    .get() (err, res, body) ->
      if res.statusCode is 200 and !err?
        ics = ical.parseICS(body)
        event_list = []
        for _, event of ics
          if event.type == 'VEVENT'
            event_list.push event.summary
        console.log("Scheduled events for " + calendar_name)
        for event, k in event_list
          console.log(event)
0

There are 0 answers