How to use ScopedClient with Iced CoffeeScript

197 views Asked by At

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?

2

There are 2 answers

0
dhilipsiva On

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)
0
Enkows On

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