0

I'm trying to rewrite a hubot script using iced coffee script. Here is my original regular (hot?) CoffeeScript code:

getHost = (msg, artifact, cb) ->
  url = "http://myapi.org/api/hosts-for/artifact/#{artifact}"
  msg.http(url)
    .get() (err, res, body) ->
      cb(body)

Note that msg.http() is making a call to the Scoped http client which you can find here: https://github.com/technoweenie/node-scoped-http-client

I would like to turn this into a function that does not use a callback but waits for the api response and returns it. Here is my attempt to convert the above into ICS:

getHostAwait = (msg, artifact) ->
  url = "http://myapi.org/api/hosts-for/artifact/#{artifact}"
  await msg.http(url)
    .get() (err, res, body) ->
      defer(body)
  body

However, the body does not appear to be returned (it is undefined). How can I get this code to work?

Alex Spurling
  • 54,094
  • 23
  • 70
  • 76

2 Answers2

1

You can try this:

getHostAwait = (msg, artifact) ->
  url = "http://myapi.org/api/hosts-for/artifact/#{artifact}"
  await msg.http(url)
    .get(), defer err, res, body
  yourCallBack body
Enkows
  • 11
  • 1
0

Because your code is asynchronous. By the time it "body" returns to the caller, it is not initialized or assigned yet. you can try sending a handle as third argument to run asynchronously. like instead of returning boby send a function called "myFunction" which can be executed async.

getHostAwait = (msg, artifact, myFunction) ->
  url = "http://myapi.org/api/hosts-for/artifact/#{artifact}"
  await msg.http(url)
    .get() (err, res, body) ->
      myFunction(body)
dhilipsiva
  • 3,688
  • 1
  • 24
  • 35