Jquery $when done then的用法詳解

字號:


    這篇文章主要介紹了Jquery $when done then的用法詳解的相關(guān)資料,本文還通過一個例子給大家介紹jquery when then(done) 用法,需要的朋友可以參考下
    對于$.ajax請求來說,如果層級比較多,程序看起來會比較亂,而為了解決這種問題,才有了$when...done...fail...then的封裝,它將$.ajax這嵌套結(jié)構(gòu)轉(zhuǎn)成了順序平行的結(jié)果,向下面的$.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) {
    }
    }
    }
    而它實現(xiàn)的功能無非就是外層執(zhí)行完成后,去執(zhí)行內(nèi)層的代碼代碼,看下面的$.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("程序出現(xiàn)錯誤!");
    }).then(function (data) {
    alert("程序執(zhí)行完成");
    });
    而對于這種ajax的封裝,在比較流行的node.js里也需要被看到,這就類似于方法的回調(diào)技術(shù)!
    在使用MVVM的KO上,更加得心應(yīng)手,感覺$.when就是為了Knockoutjs而產(chǎn)生的!
    //MVVM數(shù)據(jù)綁定
    var MyModel = new model();
    $.when($.ajax({
    url: "/home/GetProduct",
    dataType: "JSON",
    type: "GET",
    success: function (data) {
    MyModel.PeopleList = ko.observableArray(data);//先為對象賦值
    }
    })).done(function (data) {
    ko.applyBindings(MyModel);//再綁定對象
    });
    以后我們在進行前端開發(fā)時,應(yīng)該多使用這種順序的,平行的代碼段,而少用嵌套的代碼段,這只是大叔個人的見解。
    下面通過一個例子再給大家介紹jquery when then(done) 用法
    //運行條件jquery 1.82以上,直接運行代碼,看結(jié)果
    var log = function(msg){
    window.console && console.log(msg)
    }
    function asyncThing1(){
    var dfd = $.Deferred();
    setTimeout(function(){
    log('asyncThing1 seems to be done...');
    dfd.resolve('1111');
    },1000);
    return dfd.promise();
    }
    function asyncThing2(){
    var dfd = $.Deferred();
    setTimeout(function(){
    log('asyncThing2 seems to be done...');
    dfd.resolve('222');
    },1500);
    return dfd.promise();
    }
    function asyncThing3(){
    var dfd = $.Deferred();
    setTimeout(function(){
    log('asyncThing3 seems to be done...');
    dfd.resolve('333');
    },2000);
    return dfd.promise();
    }
    /* do it */
    $.when( asyncThing1(), asyncThing2(), asyncThing3() ).done(function(res1, res2, res3){
    log('all done!');
    log(res1 + ', ' + res2 + ', ' + res3);
    })
    以上所述是小編給大家介紹的Jquery $when done then的用法詳解,希望對大家有所幫助