0

I created the function below to get me a random cat fact. The top function works:

function getCatFact(callback) {
      request('http://catfacts-api.appspot.com/api/facts', function (error, resp, body) {
        if (!error && resp.statusCode == 200) {
          var jsonObj = JSON.parse(body);
          message = "Thanks for texting Cat Facts! Remember everytime you text you will receive an instant Cat Fact! "+ jsonObj.facts[0];
          return callback(message);
        }
      });
    }

calling the function with:

  getCatFact(function(returned_message){
    console.log(returned_message); // This returns the catfact fine
    response = returned_message; // Response is not correctly being set.
  });

When I call this function. Response is undefined. Response is declared at the top of the file with just var response; I then later return response.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • When do you *examine* `response`? It cannot be not set by that method, so either (a) you're looking at it too soon, or (b) something else is modifying it. – Dave Newton Jun 04 '15 at 18:31
  • getCatFact will execute asynchronously, which means that if you return response it will not be assigned yet and you will get undefined. You must wait for the asynchronous action to complete. Usually instead of returning the value a callback is used (which is what you used in the request call so it is interesting you did not just do that again with the getCatFact call. – Travis J Jun 04 '15 at 18:32
  • This was marked as duplicate but I am doing the exact same thing as the people answered from the duplicate. Thanks Matt Ball for no help at all, and just trying to be a StackOverflow police, instead of attempting to answer my question. – Greg Pappok Jun 04 '15 at 20:10

0 Answers0