I'm trying to call a weather API to get the current weather for a bot. I'm using node-rest-client to pull a description of the weather, which will be held in context.forecast
. The only problem is, I can't seem to modify/create the variable inside the function or access it outside of the function. Here's my code:
'fetch-forecast': (sessionId, context, cb) => {
var url = "http://api.openweathermap.org/data/2.5/weather?q="+context.location+"&APPID=APIKEY";
var forecast;
Client.get(url, (data, response) => {
context.forecast = data.weather[0].description;
});
cb(context);
}
context.forecast
returns undefined. Something like this doesn't seem to work either:
'fetch-forecast': (sessionId, context, cb) => {
var url = "http://api.openweathermap.org/data/2.5/weather?q="+context.location+"&APPID=APIKEY";
var forecast;
Client.get(url, (data, response) => {
forecast = data.weather[0].description;
});
context.forecast = forecast;
cb(context);
}
context.forecast
also returns undefined here. Any ideas on what I'm doing wrong?
[Edit] Tried something like this, but I'm still unable to edit the context.forecast
variable:
'fetch-forecast': (sessionId, context, cb) => {
var location = context.location;
var url = "http://api.openweathermap.org/data/2.5/weather?q="+location+"&APPID=APIKEY";
var forecast;
function getWeather(url) {
return new Promise(function(resolve, reject) {
Client.get(url, (data, response) => {
resolve(data.weather[0].description);
});
});
}
getWeather(url).then(function(result) {
context.forecast = result;
console.log(context.forecast)
}).catch(function() {
context.forecast = "not found";
});
console.log(context.forecast);
cb(context);
}
The second console.log
returns undefined
first, and the first console.log
returns the actual value second. I'm still at a loss for why this is happening.