我有这样的事情:
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.
更多推荐
我怎么知道当最后一个异步完成?
发布评论