d-_-b
d-_-b

Reputation: 23171

queue up function callbacks

A few different functions are called when an event happens. For simplicity sake, let's say I have two different analytics tracking requests sent out. They each have a callback function to redirect a visitor after the response is received.

function analytics(event,callback){
    // send analytics event;
    if (callback) callback();
}

function analytics2(event,callback){
    // send analytics2 event;
    if (callback) callback();
}

The callback function is usually:

If: tracking response is received from remote server

Then: redirect to URL

$("a").click(function(){
    analytics(
        'clicked on ' + $(this).attr('id'),
        function(){
            location.assign($(this).attr('href'));
        }
    );

    analytics2(
        'clicked on ' + $(this).attr('id'),
        function(){
            location.assign($(this).attr('href'));
        }
    );
});

Question: What's the best way to queue up these callbacks, so I wait for all callback functions to be ready before redirecting? As it's setup now, whenever the first callback runs the visitor is redirected -- without ever knowing if the server recieved the analytics2() function.

I've seen some sites use their own queue system, I just have no idea how this is implemented.

Any suggestions/thoughts?

Should I set analytics2() as the callback for anlaytics()? But then if I end up not running analytics() then analytics2() would never run. Ideally, I'd like to have a more organized approach.

Upvotes: 2

Views: 132

Answers (1)

DevlshOne
DevlshOne

Reputation: 8457

$.when(analytics(), analytics2()).done(function(a1Result, a2Result){
    ... make decisions based on a1Result and a2Result
});

This is jQuery's version of promises, allowing you to make two async calls and defer any decisions until they have both completed.

Upvotes: 2

Related Questions