0

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.

samwight
  • 129
  • 2
  • 8
  • 2
    Looks like yet another dup of this http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – elclanrs Apr 17 '16 at 19:04
  • @elclanrs I still don't understand. I tried restructuring my code using promises and it still doesn't seem to work. Can you explain? – samwight Apr 17 '16 at 19:29
  • It's asynchronous. That means sending the request (or rather receiving the response) is taken out of the normal execution flow. In your example, Client.get returns immediately and the next statement, context.forecast;, is executed before the function you passed as success callback was even called. – Quentin Apr 17 '16 at 19:42
  • @Quentin Gotcha. I think the problem was I wasn't calling `cb()` inside of the promise. I did that and now it works. Thanks! – samwight Apr 17 '16 at 19:48

0 Answers0