Track Asynchronous Calls

I am working on a Mozilla extension and have a problem when I make n calls for an asynchronous function, this function is not in my control and makes a callback at the end. In this callback, I need to perform a special action if this is the nth and last callback. I can’t figure out how to determine if the callback is final, I thought about setting up the counter and decreasing it every time, but because of the nested loop, I don’t know in advance how many asynchronous calls will be made (without preliminary development, 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);
        }
        }
    }

}

Thank.

+3
source share
1 answer

You can do something in this direction:

   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());
+1

Source: https://habr.com/ru/post/1751306/


All Articles