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