跟踪异步调用

时间:2010-06-22 23:25:19

标签: javascript

我正在研究一个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);
        }
        }
    }

}

感谢。

1 个答案:

答案 0 :(得分:1)

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

   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());
相关问题