I am writing a script for my company's Rocket Chat server using hubot. As a learning step, I decided to try getting API data from forecast.io and output certain members to the user. However, my bot will not output the JSON no matter what I try. When I try sending the entire body it only says "[object Object]" and when I try to output certain members it either send "undefined" or it doesn't send anything at all. Also, I have tried using syntax like "json['member']['member']" and like "json.member.member" (and I have seen both on the internet) and neither has worked. Any help is greatly appreciated. Thanks in advance. (NOTE: I did not include my API key which is written in the code as FORECAST_KEY)
SOLVED : I did not fully understand what node.js is all about. Node.js is event-based , meaning that it performs actions when events occur instead of performing actions in a linear order.
My problem here was that there was latency between the return of the data and the return of the function. More simply, the request wasn't completed until after the function had already returned the container, which was empty. The problem resided in me using a separate function instead of including the request straight in the code.
module.exports = (robot) ->
robot.hear /weather/i, (res) ->
testurl = "https://api.forecast.io/forecast/#{FORECAST_KEY}/37,-10"
data = httpRequest(robot, testurl, res)
res.send("Checking Weather...")
res.send("#{data['latitude']}")
res.send("#{data.latitude}")
httpRequest = (robot, url, topRes) ->
topRes.http(url)
.get() (err, res, body) ->
#If error, display error
if err
topRes.send("Bot Encountered an Error :: #{err}")
else
#Try to parse JSON
tryBody = body
try
data = JSON.parse(tryBody)
catch e
#Catch error, return plain body
return body
#If not error, return JSON
return data
Did you try adding a log statement in the httpRequest function? The httpRequest is a named function and have to be declared ahead of making a call to it.
Change the code to:
httpRequest = (robot, url, topRes) ->
topRes.http(url)
.get() (err, res, body) ->
#If error, display error
if err
topRes.send("Bot Encountered an Error :: #{err}")
else
#Try to parse JSON
tryBody = body
try
data = JSON.parse(tryBody)
catch e
#Catch error, return plain body
return body
#If not error, return JSON
return data
module.exports = (robot) ->
robot.hear /weather/i, (res) ->
testurl = "https://api.forecast.io/forecast/#{FORECAST_KEY}/37,-10"
data = httpRequest(robot, testurl, res)
res.send("Checking Weather...")
res.send("#{data['latitude']}")
res.send("#{data.latitude}")
Reference: https://softwareengineering.stackexchange.com/questions/191196/coffeescript-and-named-functions
Hope this helps.
Thanks, Phani.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.