0

Consider the following setup, regarding asynchronous functions:

Client.prototype.auth = function(callback) {
    //authenticate the client
    //run callback
};

Client.prototype.get = function() {
    this.auth(function(){
        //run the rest of this `get` function
    }
};
  • The get function is called numerous times through an eventlistener, and this event fires only once
  • The very first get should start the authentication which stays valid for every subsequent calls
  • The authentication function is takes a couple of seconds to complete
  • Every subsequent get call does not need to reauthenticate because it is still valid because of the first function call
  • Every subsequent get call should only be run after the client is authenticated. If it is not authenticated it should wait for the authentication to finish

The point is to prevent 10 get calls to fire 10 auth calls. Whenever the 1st auth function gets called, the other 9 get calls should wait for it to finish and then carry on with the rest of the get function (while being authenticated)

I cant get my head around this. I tried to keep this example as simple as possible

Flame
  • 6,663
  • 3
  • 33
  • 53

1 Answers1

1

I think solution for you is caching. Make a cache that will hold value isUserAutheniticated and isAuthenitcationProcess and when you need to call auth just check if user is authenticated and if not call it. Inside auth subscribe callback, check if authentication process is open if not do authentication set and call all registered callbacks. Globallist is not cleanest option to implement Observable pattern so you can do it in other way

Here is my idea:

var isAuthenticated = false;
var isAuthenticatioProcess = false;
var authenticationCallbacks = [];
Client.prototype.auth = function(callback) {
    authenitcationCallbacks.push(callback);
    if (isAuthenticonProcess) {           
       return;
    }
    //authenticate
    authenitcationCallbacks.forEach(function(call) {
        call();
    });
    authenitcationCallbacks = [];
    isAuthenticonProcess = false;
    isAuthenticated = true;
};

Client.prototype.get = function() {
    if (isAuthenticated) {
        this.auth(function(){
            //run the rest of this `get` function
        }
    } else {
        function(){
            //run the rest of this `get` function
        }
    }
};

If you could use Async.js look at this answer

Community
  • 1
  • 1
janisz
  • 6,292
  • 4
  • 37
  • 70
  • "Inside auth check if authentication process is open if true wait on this variable until it ends periodically checking status (busy waiting), to prevent it you can keep list of subscribers that should be notified inside auth's callback" that part confuses me, how would you loop that 'periodically checking' thing and how do you callback all the `get` functions? I have [link](http://underscorejs.org/) available if that might help – Flame Jan 21 '15 at 14:14