模拟同步 XmlHttpRequest
我读过一些其他相关问题(包装异步 JavaScript 函数以使其同步的模式 &进行异步JavaScript 中的事件同步 可能还有更多),但我只是想确保穷尽所有可能性。
是否可以使用 setInterval 或 setTimeout 将异步 XmlHttpRequest“转换”为准同步请求?
这个想法是,Ajax 请求成功后,将设置一个变量,该变量将作为 while 循环(已调用 setInterval 或 setTimeout,以及适当的回调函数)退出的信号。或者我从根本上误解了 setInterval 和/或 setTimeout 的能力(或限制?)?
I've read some of the other related questions (Pattern for wrapping an Asynchronous JavaScript function to make it synchronous & Make async event synchronous in JavaScript & there may be more), but I just want to be sure to exhaust all possibilities.
Might it be possible to "convert" an asynchronous XmlHttpRequest into a quasi-synchronous one using either setInterval or setTimeout?
The idea being that upon success of the Ajax request a variable will be set, which will be the signal for a while loop (that has called either setInterval or setTimeout, and a callback function as appropriate) to exit. Or am I fundamentally misunderstanding the abilities (or limitations?) of setInterval and/or setTimeout?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
确实,您不想按照您所描述的方式使用 setInterval 和 setTimeout 。您真正想做的只是熟悉嵌套函数,您可以在其中以或多或少同步的方式进行编写。
例如:
虽然您可以使用 setInterval 和/或 setTimeout(在函数体中再次调用 setTimeout)来“轮询”成功代码,但这种方法明显不如首先处理回调而不是轮询它。它会带来延迟,占用 CPU 资源,并且无法跨多个 XHR 请求进行扩展,等等。
XHR 将在完成时调用您的函数,运行一个函数询问“我们完成了吗?我们完成了吗?”是没有意义的。同时。另一方面,如果您希望阻止某些周期性行为,直到响应返回(例如,一段需要该数据运行的动画),则完全可以接受将阻止代码包含在 if 语句中:
It's true, you don't want to use setInterval and setTimeout in the way you've described. What you really want to do is just get comfortable with nested functions, where you can write in a more or less synchronous way.
For example:
While you can use setInterval and/or setTimeout (with calls to setTimeout again in the function body) to "poll" for a success code, that approach is dramatically inferior to just handling the callback in the first place instead of polling for it. It introduces latency, runs away with the CPU, and doesn't scale across multiple XHR requests, to name a few shortcomings.
XHR will call your function when it completes, it makes little sense to run a function asking "Are we done yet? Are we done yet?" in the meantime. On the other hand if there is some periodic behavior you are wanting to BLOCK until the response comes back (a piece of animation that needs that data to run, for example) it is totally acceptable to surround the blocking code in an if statement:
如果我正确回答了您的问题,您可以使用以下代码实现类似的效果:
If I'm getting your question right, you could achieve a similar effect using the following code: