2010-06-22 60 views
3

我正在使用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

你可以做一些沿着这些路线:

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

谢谢。这看起来不错,但有可能在下一次迭代循环之前执行回调?即创建回调 - >回调执行 - > is_final,全部在下一次循环迭代之前完成。还是保证在最后一个函数在循环中调用前,requestsWaiting将保持大于0? – 2010-06-23 02:44:00

+0

@Jason Gooner - 是的,你可以在'setTimeout(function(){'...'},0)中实际包装if;'解决这个问题,当不在我的手机上时编辑:) – gnarf 2010-06-23 07:44:03