jQuery的ajax链式编程方法

在开发的过程,常常会遇到一些耗时间的操做,好比ajax读取服务器数据(异步操做),遍历一个很大的数组(同步操做)。无论是异步操做,仍是同步操做,总之就是不能当即获得结果,JS是单线程语音,不能当即获得结果,便会一直等待(阻塞)。html

通常的作法就是用回调函数(callback),即事先定义好一个函数,JS引擎不等待这些耗时的操做,而是继续执行下面的代码,等这些耗时操做结束后,回来执行事先定义好的那个函数。以下面的ajax代码:ajax

$.ajax({
    url: "test.html",
    success: function(){
        console.log("success");
    },
    error: function(){
        console.log("error");
    }
});

但这样写不够强大灵活,也很啰嗦。为此,jQuery1.5版本引入Deferred功能,为处理事件回调提供了更增强大而灵活的编程模式。编程

$.ajax("test.html")
.done(
    function(){
        console.log("success");
    }
)
.fail(
    function(){
        console.log("error");
    }
);

不就是链式调用嘛,有何优势?数组

优势一:能够清晰指定多个回调函数服务器

function fnA(){...}
function fnB(){...}
$.ajax("test.html").done(fnA).done(fnB);

试想一下,若是用之前的编程模式,只能这么写:异步

function fnA(){...}
function fnB(){...}
$.ajax({
    url: "test.html",
    success: function(){
        fnA();
        fnB();
    }
});

优势二:为多个操做指定回调函数函数

$.when($.ajax("test1.html"), $.ajax("test2.html"))
.done(function(){console.log("success");})
.fail(function(){console.log("error");});

用传统的编程模式,只能重复写success,error等回调了。url

相关文章
相关标签/搜索