2

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.

5
  • Try promises! Commented Aug 11, 2013 at 15:59
  • Suppose we can get the two analytics to run at the same time, are you looking to use the recommended redirect from the first one that receives a response or are you planning to compare results before making a redirect decision? Commented Aug 11, 2013 at 16:00
  • I don't think i'll be comparing anything. I'd just need to make sure both responses are received, and most likely will redirect to the same place for all of these functions. Commented Aug 11, 2013 at 16:01
  • 1
    Check out the jQuery .deferred() and .then() methods. api.jquery.com/jQuery.Deferred Commented Aug 11, 2013 at 16:02
  • 1
    so where's the call to analytics2? Commented Aug 11, 2013 at 16:04

1 Answer 1

2
$.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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.