gpt4 book ai didi

javascript - 跟踪异步调用

转载 作者:行者123 更新时间:2023-11-29 15:53:04 27 4
gpt4 key购买 nike

我正在开发一个 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());

关于javascript - 跟踪异步调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3097871/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com