我怎么知道当最后一个异步完成? [英] How do I know when the last async is done?

查看:107
本文介绍了我怎么知道当最后一个异步完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的事情:

for (var i=0;i<result.qry.ROWCOUNT;i++) {
  myAsync(i);
}

我如何知道我所有的异步函数执行完毕?

How do I know when all my Async functions have finished executing?

目前有人回答的风险需要更多的jQuery的!,我可以使用jQuery的承诺对象吗?或延期或者类似的东西?

At the risk of someone replying with "Needs more jQuery!", can I use the jQuery promise object? Or deferred or something like that?

推荐答案

跟踪的异步调用多少都很优秀。当每完成后,你的递减计数器。当你为0,你是最后一个回调。

Keep track of how many asynchronous calls are outstanding. When each finishes, decrement your counter. When you get to 0, you are in the last callback.

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的单线程性质存在这样的情况之前,所有的异步调用已排队你可能会回调调用没有潜在的竞争状态。它是安全的,把 asyncsLeft ++ 调用后 doSomethingAsynchronous ,如果你喜欢。

Due to the single-threaded nature of JavaScript there is no potential race condition where you might get your callback invoked before all of the asynchronous calls have been queued up. It is safe to put the asyncsLeft++ call after the doSomethingAsynchronous, if you like.

这篇关于我怎么知道当最后一个异步完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆