我怎么知道当最后一个异步完成?

编程入门 行业动态 更新时间:2024-10-27 00:32:59
本文介绍了我怎么知道当最后一个异步完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有这样的事情:

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.

更多推荐

我怎么知道当最后一个异步完成?

本文发布于:2023-08-02 13:27:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1278178.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:我怎么

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!