jmoon
jmoon

Reputation: 576

globals or passing functions

Trying to pass something to something else. Says undefined. Not sure how or why.

clsapp.on 'mysqld', ->
  getHostById = (host) -> cls.getHostById.acq host, (c) -> JSON.stringify(result)

I need some way to access getHostById('localhost').hostname while inside another part of the .js

clsapp.on getHostById('localhost'), (c) ->   
  console.log JSON.parse(getHostById('localhost')).hostname

is just null or undefined

Upvotes: 1

Views: 55

Answers (1)

Trevor Burnham
Trevor Burnham

Reputation: 77416

It's hard to understand what you're asking, but I'll make some observations:

In the code

clsapp.on 'mysqld', ->
  getHostById = (host) -> cls.getHostById.acq host, (c) -> JSON.stringify(result)

you probably meant for the callback argument to be called result, not c. Unless you're defining result elsewhere.

More importantly, there has got to be a clearer way for you to write this code. Just expanding the definition of getHostById to be multi-line helps a bit:

clsapp.on 'mysqld', ->
  getHostById = (host) ->
    cls.getHostById.acq host, (result) -> JSON.stringify(result)

Now, I think that ultimately, your problem is that you're trying to make an async function behave synchronously—which you can't do in JavaScript (or CoffeeScript, which is a thin syntactic layer on top of JS). Since cls.getHostById.acq takes a callback, it's almost certainly designed to call that callback after it returns so that it doesn't block the thread. Which means that there's no way for you to write a getHostById function that simply returns a value, as your JSON.parse(getHostById('localhost')) example suggests. You'll have to use a callback.

Upvotes: 1

Related Questions