繁体   English   中英

跟踪异步调用

[英]Keeping track of asynchronous calls

我正在研究一个Mozilla扩展,并且遇到一个问题,即我对异步函数进行n次调用,该函数不受我的控制,并且在完成时执行回调。 在这个回调中,如果是第n次和最后的回调,我需要采取特殊行动。 我无法确定如何确定回调是否是最后一个,我考虑设置一个计数器并每次递减它,但由于嵌套循环我不知道预先会有多少异步调用(没有提前解决这个效率低下的问题)。 关于优雅方法的任何想法?

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);
        }
        }
    }

}

谢谢。

你可以沿着这些方向做点什么:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM