Javascript function returns undefined in firebug

Possible duplicate:
How to return a response from an AJAX call from a function?

in my application namespace, I just defined a function:

version 1

window.App = {
  isLogged: function () {
    $.get('/user/isLogged', function (data) {
      if (data == 'true') {
        return true;
      }
      return false;
    });
  }
};

      

version 2

window.App = {
  isLogged: function () {
    var test = $.get('/user/isLogged');
    console.log(test.responseText);
  }
};

      

In version 1, when I try to use firebug 'App.isLogged () function, I got nice undefined: S

In version 2, when I try to execute a function on firebug, the responseText looks like undefined: stuck:

I am new to javascript and maybe a scope problem ...

The purpose of my function is clear, I think there is a better way to achieve this?

+3


source to share


1 answer


in the first version $.get

is asynchronous, so you don't get the return value

on the second version it $.get

returns a deferred object that has no fieldresponseText



window.App = {
  isLogged: function () {
    var dfd = $.Deferred();
    $.get('/user/isLogged', function (data) {
      if (data == 'true') {
        return dfd.resolve();
      }
      return dfd.reject();
    });
    return dfd.promise();
  }
};

$.when(App.isLogged()).then(function() {
  //your code
}).fail(function() {
  //fail code
});

      

+2


source







All Articles