0
function getCatFact() {
  var catFact = "";
  request('http://catfacts-api.appspot.com/api/facts', function (error, resp, body) {
      var jsonObj = JSON.parse(body);
      catFact += jsonObj.facts[0];
  })
    console.log("HERE IT IS: "+catFact);
    return "Here is your CatFact" + catFact;
}

Seems very simple but I am doing something wrong. All this function returns is Here is your CatFact.. I tried putting the return inside the request function as well, with no luck. Would love any help.

1 Answers1

3

The request is asynchronous. That means that the request will fire, and JavaScript will immediately move on the the next line before the response has made it back to the client. In your case, the stuff that prints the cat fact.

Returning the cat fact itself will not work in this instance, because you will return it before the response has returned and changed the empty string. You either need to call a function within the success callback or return the request object itself.

Brennan
  • 5,632
  • 2
  • 17
  • 24