我有这样的事情:如何知道最后的异步完成时间?
for (var i=0;i<result.qry.ROWCOUNT;i++) {
myAsync(i);
}
我怎么知道什么时候我所有的异步函数执行完毕?
如果有人回答“需要更多jQuery!”,我可以使用jQuery承诺对象吗?或推迟或类似的东西?
我有这样的事情:如何知道最后的异步完成时间?
for (var i=0;i<result.qry.ROWCOUNT;i++) {
myAsync(i);
}
我怎么知道什么时候我所有的异步函数执行完毕?
如果有人回答“需要更多jQuery!”,我可以使用jQuery承诺对象吗?或推迟或类似的东西?
在jQuery中,有最后一个Ajax运行后运行的$.ajaxStop
函数。
跟踪有多少异步调用未完成。当每个完成时,减少你的柜台。当你达到0时,你处于最后一次回调。
var asyncsLeft = 0;
for (var i=0;i<10;++i){
asyncsLeft++;
doSomethingAsyncWithCallback(function(){
// This should be called when each asynchronous item is complete
if (--asyncsLeft==0){
// This is the last one!
}
});
}
是因为JavaScript的单线程性质存在这样的情况之前,所有的异步调用已排队,你可能会得到您的回调调用没有潜在的竞争状态。如果您愿意,可以在doSomethingAsynchronous
之后拨打asyncsLeft++
电话。
我建议类似的东西:使用两个变量,一个用于分配资源总数,另一个用于跟踪已加载/失败的数量(可能还有两个其他变量)。只要有一个变量,你就有可能在代码创建一个新的请求之前完成一个请求,而这个请求会过早地假设所有的东西都被加载(是的,这实际上发生在我身上)。另外,使用两个变量可以显示加载资源的进度。 –
@JeffreySweeney如果你在一个循环中全部踢掉它们,那么不,你不会冒这个风险。这就是我斜体文字的意思。直到'for'循环完成后才会开始调用回调。 – Phrogz
使用一个回调函数:
for (var i=0;i<result.qry.ROWCOUNT;i++) {
myAsync(i, myCallback);
}
function myCallback(i){
//set result.qry.ROWCOUNT to a var somewhere above if it's not available in this scope
if(i == (result.qry.ROWCOUNT - 1)){
//now you know you're actually done with all requests
}
}
function myAsync(i,callback){
///do work
callback(i);
}
这只有在异步任务按照它们开始的顺序完成时才有效。 –
在这种情况下,'myAsync'是同步的,您必须将回调传递给您正在使用的任何异步方法/库。 –
优点 –
如果你使用jQuery,您还可以使用ajaxSend
和ajaxComplete
方法,让您的计数器代码从代码派遣独立。
var ajaxPending = 0;
function ajax_changed(indicator, pending) {
if (pending)
$(indicator).show();
else
$(indicator).hide();
}
$('#loading-indicator').ajaxSend(function() {
ajax_changed(this, ++ajaxPending);
});
$('#loading-indicator').ajaxComplete(function() {
ajax_changed(this, --ajaxPending);
});
这是我会怎么做:
//Do stuff up here to get records
var rowCount = result.qry.ROWCOUNT, //Save the row count
asyncCount = 0, //The count of complete async calls
asyncCallback = function() {
//To be called whenever an async operation finishes
asyncCount++; //Increment the row counter
if (asyncCount >= rowCount) {
//Do stuff when they're all finished
}
};
for (var i=0;i<rowCount;i++) {
myAsync(i, asyncCallback);
}
function myAsync(index, completeCallback) {
//Do async stuff with index
//Call completeCallback when async stuff has finished or pass it
// into the async function to be called
}
使用jQuery你可以用'.done()'或'。那么()'和'$。当(合并)':HTTP ://stackoverflow.com/a/5817886/1095206 – BartekR
非常感谢。这是我一直在寻找的东西! –