jquery的 异步加载$.when

$.when()方法

$.when()接受多个deferred对象作为参数,当它们全部运行成功后,才调用resolved状态的回调函数,但只要其中有一个失败,就调用rejected状态的回调函数。它相当于将多个非同步操作,合并成一个。实质上,when方法为多个deferred对象,返回一个单一的promise对象

$.when(
    $.ajax( "/main.php" ),
    $.ajax( "/modules.php" ),
    $.ajax( "/lists.php" )
).then(successFunc, failureFunc);

上面代码表示,要等到三个ajax操作都结束以后,才执行then方法指定的回调函数。

when方法里面要执行多少个操作,回调函数就有多少个参数,对应前面每一个操作的返回结果。

$.when(
    $.ajax( "/main.php" ),
    $.ajax( "/modules.php" ),
    $.ajax( "/lists.php" )
).then(function (resp1, resp2, resp3){
    console.log(resp1);
    console.log(resp2);
    console.log(resp3);
});

上面代码的回调函数有三个参数,resp1、resp2和resp3,依次对应前面三个ajax操作的返回结果。

如果when方法的参数不是deferred或promise对象,则直接作为回调函数的参数。

上面如果,返回值是一个变量,则直接拿取变量,并且是按照$.when里面的排序,按照顺序返回数据的

jquery的 defer解决地狱回调(异步请求,回调里面嵌套ajax请求的这种)

对于$.ajax请求来说,如果层级比较多,程序看起来会比较乱,而为了解决这种问题,才有了$when...done...fail...then的封装,它将$.ajax这嵌套结构转成了顺序平行的结果,向下面的$.ajax写法,看起来很乱

$.ajax({
url: "/home/GetProduct",
dataType: "JSON",
type: "GET",
success: function (data) {
$.ajax({
url: "/home/GetProduct",
dataType: "JSON",
type: "GET",
success: function (data) {
$.ajax({
url: "/home/GetProduct",
dataType: "JSON",
type: "GET",
success: function (data) {
}
}
}

而它实现的功能无非就是外层执行完成后,去执行内层的代码代码,看下面的$.when写法,就清晰多了

$.when($.ajax({
url: "/home/GetProduct",
dataType: "JSON",
type: "GET",
success: function (data) {
alert(JSON.stringify(data));
}
})).done(function (data) {
alert(data[0].Name);
}).done(function (data) {
alert(data[1].Name);
}).fail(function () {
alert("程序出现错误!");
}).then(function (data) {
alert("程序执行完成");
});

猜你喜欢

转载自blog.csdn.net/dxj124/article/details/82786959