-1

I'm using express, node, and handlebars. I have this bit of code for handling POSTs. If the user clicks the "add item" button, it takes their entry for a city, looks up the weather for that city using the Open Weather Map API, and changes the color around the background of that city item based on the weather.

app.post('/',function(req,res){
  var context = {};
  var temperature;

  if(req.body['Add Item']){
    req.session.toDo.push({"name":req.body.name, "id":req.session.curId, "location":req.body.city});
    req.session.curId++;

    request('http://api.openweathermap.org/data/2.5/weather?q=' + req.body.city + '&units=imperial&APPID=' + credentials.owmKey, handleGet);

    function handleGet(err, response, body){
      if(!err && response.statusCode < 400){
        context.owm = body;
        var newText = JSON.parse(context.owm);
        temperature = newText.main.temp;
      } 
    }
  }
...

  if(temperature > 70) {
    context.script = "<script>document.getElementById('owm').style.backgroundColor='LightGreen';</script>"
  }

  else if (temperature < 70){
    context.script = "<script>document.getElementById('owm').style.backgroundColor='LightPink';</script>"
  }
}

However, the temperature variable is returning 'not defined'. I figure this has to do something with asynchronicity, but I'm not sure what I should do to correct it.

Taylor Liss
  • 593
  • 4
  • 27
  • 1
    **you don't**. It's not a scoping problem, it's a timing problem. You have no idea when the request returns, the request handler is fired and therefore `temprature` is available. You have to put/call all the logic that depends on `temperature` inside the request handler. – Thomas Mar 08 '17 at 21:25
  • 1
    Close to a dup of: [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call). – jfriend00 Mar 09 '17 at 00:34

1 Answers1

0

you can write code like this

   function handleGet(err, response, body){
      if(!err && response.statusCode < 400){
        context.owm = body;
        var newText = JSON.parse(context.owm);
        temperature = newText.main.temp;
        if(temperature > 70) {
          context.script = "<script>document.getElementById('owm').style.backgroundColor='LightGreen';</script>"
        } else if (temperature < 70){
          context.script = "<script>document.getElementById('owm').style.backgroundColor='LightPink';</script>"
        }
        console.log('temp inside is '+ temperature);
      } 
    }
Gaurav Kumar Singh
  • 1,550
  • 3
  • 11
  • 31