Bar*_*rka 6 javascript ajax jquery json
我正在对服务器进行ajax调用.我需要运行的代码可以分为3组.
在进行ajax调用之后和结果返回之前运行第3组中的代码是理想的,以获得最佳用户体验和性能.
可以这样做吗?
怎么样?
非常简单:
function someFunction() {
//1. code that needs to run before ajax
$.ajax({...}).done(function () {
//2. code that needs to be run after the ajax call has returned
});
//3. code that needs to be run between the time the user presses
// a button and the time everything is done.
}
Run Code Online (Sandbox Code Playgroud)
这是有效的,因为JavaScript在执行时是同步的(除非正在使用工作程序,但这与此特定问题无关).第一位代码将运行,然后ajax调用将告诉浏览器启动XHR请求,但someFunction尚未完成,因此它将继续同步执行.
一旦someFunction完成,控制流将陆续开放中发生的任何异步事件,最终导致done回调.
公平地说,异步的面向事件的编程对于大多数人来说并不容易.很容易忘记在什么时间发生什么代码.
以下是异步行为如何工作的易于执行的示例:
(function () {
alert(1);
setTimeout(function () {
alert(2);
}, 0); //note the 0ms delay
alert(3);
}());
Run Code Online (Sandbox Code Playgroud)
警报的顺序将是1,3,2.setTimeout不会同步调用它的回调,因为它依赖于等待指定的时间量,所以即使没有时间过去,它仍然必须等待当前函数完成才能继续.
| 归档时间: |
|
| 查看次数: |
1607 次 |
| 最近记录: |