tags:

views:

42

answers:

1

Hi,

I'm working on a Mozilla extension, and have a problem where I make n calls to an asynchronous function, that function is out of my control and it executes a callback on completion. In this callback, I need to take a special action if it's the n'th & final callback. I can't work out how to determine if a callback is the final one, I thought about setting a counter and decrementing it each time, but due to the nested loop I don't know in advance how many async calls will be made (without working it out in advance which would be inefficient). Any ideas on an elegant approach to this?

function dataCallBack(mHdr, mimeData)
{
    // ... Do stuff ...
    // Was this the final callback? 
}

function getData() {
    var secSize = secList.length;

    for (var i = 0; i < secSize; i++) {
        if (secList[i].shares.length >= secList[i].t) {

        var hdrCount = secList[i].hdrArray.length;

        for(var j = 0; j < hdrCount; j++)
        {
                    // MAKE ASYNC CALL HERE
            mozillaFunction(secList[i].hdrArray[j], this, dataCallBack);
        }
        }
    }

}

Thanks.

A: 

You could do something along these lines:

   var requestsWaiting = 0;
   // this will be the function to create a callback
   function makeDataCallback() {
     requestsWaiting++; // increase count
     // return our callback:
     return function dataCallBack(mHdr, mimeData)
     {
       // ... Do stuff ...
       // per request - make sure that this happens in the next event loop:
       // can be commented out if not needed.
       setTimeout(function() {
         // Was this the final callback? 
         if (! --requestsWaiting) {
            // it was the final callback!
         }
       // can be commented out if not needed
       },0);
     }
   }

// then in your loop:
// MAKE ASYNC CALL HERE
mozillaFunction(secList[i].hdrArray[j], this, makeDataCallBack());
gnarf
@gnarf, thank you. That looks good, but is it possible that a callback could be executed before the next iteration of the loop? i.e create callback -> callback executed -> is_final, all before the next loop iteration is made. Or is it guaranteed that requestsWaiting will remain > 0 until the last function call in the loop?
Jason Gooner
@Jason Gooner - Yeah, you could actually wrap the if in a `setTimeout(function(){` ... `},0);` to combat that, will edit in when not on my phone :)
gnarf