1
function stRequest(type){
  switch(type){
    case "favourites":
      $.getJSON("js/favourites.json")
      .done(function(data) {
        var message = "";
        $.each(data.favourites, function(){
          message += "<a href=\"#\" class=\"favourite-user\">" + this + "</a>";
        });
        return message;
      });
      break;
  }
}

When run using something like console.log(stRequest("favourites")); it always returns undefined. In short, what's the problem with my function?

Benedict Lewis
  • 2,733
  • 7
  • 37
  • 78
  • Always remember that the **a** in _ajax_ (i.e. what's done with `getJSON`) stands for _asynchnonous_ – Paul S. Mar 20 '14 at 12:29

2 Answers2

4

You're returning from the inner function.

You'd need to return from the outer function.

You need to pass a callback to be called inside of done() or use a promise. You could then resolve the callback with message as the argument.

alex
  • 479,566
  • 201
  • 878
  • 984
1

A promise is definitely the way to go. Check out Q.

function stRequest(type){
   var deferred = Q.defer();
   switch(type){
    case "favourites":
      $.getJSON("js/favourites.json")
      .done(function(data) {
        var message = "";
        $.each(data.favourites, function(){
          message += "<a href=\"#\" class=\"favourite-user\">" + this + "</a>";
        });
        deferred.resolve(message);
      });
      break;
  }
  return deferred.promise;
}

You would then call your function like so:

stRequest('favourites').then(function(message){
  alert(message);
});
bluetoft
  • 5,373
  • 2
  • 23
  • 26
  • Would it be possible to do the same thing with `$.Deferred();` as I am already using jQuery and am hesitant to add another script if unneeded? – Benedict Lewis Mar 20 '14 at 12:37
  • @BenedictLewis https://github.com/kriskowal/q/wiki/Coming-from-jQuery – bluetoft Mar 20 '14 at 12:41
  • @BenedictLewis I haven't used jQuery's version but looks pretty similar. http://api.jquery.com/deferred.promise/ – bluetoft Mar 20 '14 at 12:45