使用 javascript 同步数组
我想知道是否有一种方法可以在 JavaScript 中同步对象/方法,就像在 Java 中一样。我正在为 html5 中的新 WebSocket 开发一个接口,并且需要一种方法来将传出请求与传入响应相匹配。因此,我将请求(具有唯一的 ID)保存在客户端的数组中,然后当我收到响应以查找匹配的请求时,我会迭代该数组。
客户端可能出现的问题是,如果我有多个计时器,它们彼此独立地向服务器发出请求。如果请求函数在响应侦听器迭代数组的同时将“请求引用”插入数组,那么它必然会中断!
那么我该如何解决这个问题呢?我最初的想法是简单地同步数组,就像在 Java 中所做的那样(在对象上加锁并强制其他函数等待),但我没有找到如何在 JavaScript 中执行此操作的语法。
I wonder if there is a way to synchronize objects/methods in JavaScript in a similar way that you can do it in Java. I am developing an interface for the new WebSocket in html5 and need a way to match outgoing requests with incoming responses. Therefore I'm saving the requests (with a unique id) in an array on the client side and then I iterate through the array when I receive a response looking for the matching request.
A problem that might occur on the client side is if I have multiple timers that are making requests to the server independently of each other. If a the request function is inserting a "request-reference" into the array at the same time as the respond-listener is iterating through the array it's bound to break!
So how do I solve this problem? My initial thoughts was to simply synchronize the array as one could have done in Java (putting a lock on the object and force the other functions to wait) but I have found no syntax of how I would do this in JavaScript.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Javascript 在浏览器中以单线程运行,因此不需要同步。
有关详细信息,请参阅此处。另请参阅这个SO问题和答案(为什么JavaScript不支持多线程?) 。
Javascript runs in a single thread in the browser, so there is no need to synchronize.
See here for details. See this SO question and answers as well (Why doesn’t JavaScript support multithreading?).