How to wrap $.ajax.then() correctly?

How to wrap $.ajax.then() correctly?

Hi there,

I'm new to this forum, hoping someone can help me out understanding promises and deferrals correctly.

in a small hobby project i'm using an ajaxwrapper like this:

var APIlib = {
  'ajaxWrapper' : function (url, params) {
          return $.ajax({
              type: type,
              url: url,
              async: false,
              data: JSON.stringify(params),
          });
   },
};

loading this snippet first, in my following code i can use

APIlib.ajaxWrapper("url", data).then(
  //use results to update my web-app...
);

(i have shortened the above snippet a bit, it is working fine)

as the restful services require login tokens, i can easily include this in the above wrapper. still, for invalid login data i have to check in every ".then()" code.

It would be much nicer if i can check this in the wrapper and redirect to the login site from there directly  - or return the retrieved result.

this is where i get stuck with async-mode

i envision sth like this inside the wrapper:

result = $.ajax ({config});

result.done(
function (result) {
 //check result
 return result;
}
);

result.fail() {
 //redirect to login
}

this of course fails bc ajaxWrapper().then() in the other code fails as the async exection of the wrapper doesn't return sth to wait on.

can someone please hook me up on this?


Thanks,