Search code examples
coffeescripthubot

CoffeeScript Hubot help: getting data from a function


I'm a novice in need of some Hubot/CoffeeScript help.

I have several responses which will get data from the same source but use and respond to different pieces of the payload. For example...

module.exports = (robot) ->
    robot.hear /score/i, (msg) ->
        score = getScore(today)
        msg.send "today's score is " + score
    robot.hear /yesterday's score/i, (msg) ->
        score = getStore(yesterday) ->
        msg.send "yesterday's score was " + score

The process of building the URL for the score data includes looking up the current month, day and year. I don't want to do that more than once but I will have many responses like the above which use the same data. I had expected I could do this.

getScore = (day) ->
    #build the url and get the data set
    #pick the right piece of data based on the day variable and assign it to score'

I guess this doesn't work because it's async. But, doing msg.send from within the getScore function doesn't work. So, how do I do this so that I don't have to repeat the getScroe code in every robot.hear section?

Thanks!


Solution

  • Pseudo code:

    getScore = (day, callback) ->
          # get the score...
          callback(score)
    
    
    robot.hear /yesterday's score/i, (msg) ->
        getScore "yesterday", (score) ->
            msg.send "yesterday's score was " + score