I'm new to using async calls in ajax. My problem is that I have two server "tasks": one that just checks if session is set (fast), and another that sets the session (slower). I want to check if the session is set and if not, set it. And I want to try X number of times (I'm unsure if I really need to but that, but that is another question). If I just do it with a “while” or a “for” and not do think about that it is async, I will generate problems like to many calls, and it will not be check session then set session. I could to it on the server, but I do not want to send the request data if session is set, only if it is not set. Below is the way I'm trying to do it now, but I'm unsure if there is a better way of doing it? The code below just implements the idea and is not tested.

The idea is that send the counter back and forth between checking and sending session in the success function. What I do not like about the code is that the set session really is just understandable in context of checkSession. If I in some time come back to the code and just want to setSession, I would have a magic number of X to make sure it does not check the session also. Is there a smoother way of doing this? If the code smells even worse, please tell me.

self.start = function() {
self.checkSession = function(count) {
        if(returnValue == false && count < 4){
self.setSession = function(count) {
      var sessionData = someData;
      server.SetSession(sessionData, function(d){
}, function(err){});};
  • 1
    Javascript side-note: I find the "Promise" pattern extremely useful for AJAX, and asynchronous stuff in general. (intro)
    – Darien
    Jan 17, 2014 at 22:34

2 Answers 2


Why not just use one call setOrReturnSession, which either returns the current session if it's already set, or creates a new session and returns that.

Yes it's marginally slower to send your session data across the wire on every call, but it's much much faster than running both calls synchronously almost every time.

It also means that all your session logic stays on the server where it belongs, rather than having it smeared across the client and server the way you do now.


I think you must call your first ajax synchronously using declared async = false; in your ajax call.

It will call your asynchronous ajax function synchronously so that after getting response from the ajax it will execute next code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.