Keeping track of asynchronous calls
<p>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 &amp; 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?</p>

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

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

    for (var i = 0; i &lt; secSize; i++) {
        if (secList[i].shares.length &gt;= secList[i].t) {

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

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

}
</code></pre>

<p>Thanks.</p>
