jQuery的deferred对象

    /**
     * 1、普通请求
     **/
    // $.ajax({
    //     url:"a.html",
    //     success: function(data){
    //         console.log(data)
    //         $("#box").html(data)
    //     },
    //     error:function(){
    //         alert("error")
    //     }
    // })


    /**
     * 2、同一操作多回调
     **/
    // $.ajax('a.html')
    // .done(function (data) {
    //     alert("a")
    //     $("#box").html(data)
    // })
    // .fail(function (data) {
    //     console.log("fail")
    // })
    // .done(function (data) {
    //     alert("b")
    //     $("#box").append('done2222')
    // })


    /**
     * 3、 多个请求,同一回调
     **/
     // $.when($.ajax('a.html'),$.ajax('b.html'))
     // .done(function (dataA,dataB) {
     //     // for(i in data){
     //     //     console.log(data[i])
     //     // }
     //     console.log("a--",dataA[0])
     //     console.log("b--",dataB[0])
     // })
     // .fail(function (data) {
     //     console.log("error")
     // })
    
     /**
     * 4、 耗时操作; 如何让耗时比较久的请求,按顺序出牌
     **/
     // var wait = function (){
     //     var task = function () {
     //         console.log("wait还没完呢; 假设的耗时请求完毕")
     //     }
     //     setTimeout(task,3000)
     // }
     // $.when(wait())
     // .done(function (data) {
     //     console.log("这是done操作; wait操作,3秒耗时完成了么???",data)
     // })
     // .fail(function () { console.log("error") })
     //done方法会立刻执行,wait还没完成,done是得不到回调的。
     //原因是$.when()的参数只能是 deferred 对象
     //所以必须对 wait() 改写
    
     //改写 例子 一、
     // var wait = function (delay) {
     //     var task = function () {
     //         $.ajax({
     //             url: 'a.html',
     //             success:function (data) {
     //                 console.log("wait",data)
     //             }
     //         })
     //     }
     //     setTimeout(task, 3000)
     //     return delay;
     // }
     // $.when(wait(delay))
     // .done(function (data) {
     //     console.log("成功了么?",data)
     // })
     // .fail(function () { console.log("error") })

    //改写 例子 二、
     var delay = $.Deferred();
     var wait = function (delay) {
         $.ajax({
             url: 'a.html',
             success:function (data) {
                 // console.log("success",data)
                 $("#box").append("<p>AAAAAA</p>")
                 var task = function () {
                     console.log("task: wait 3秒吧。")
                 }
                 delay.resolve();//delay对象的执行状态从"未完成"改为"已完成",从而触发done()方法。
                 setTimeout(task,3000)
             }
         })
     }
     $.when(wait(delay))
     .done(function (data) {
         console.log(".done: ",delay)
         console.log(".promise: ",delay.promise())
         $("#box").append("<p>BBBBBB</p>")
     })
    
     /**
     * 4、 执行状态-deferred.resolve()和deferred.reject()
     * deferred.reject()deferred对象的执行状态从"未完成"改为"已失败",从而触发fail()方法。
     **/

注:整理自   阮一峰的网络日志

原文地址:https://www.cnblogs.com/clj2017/p/9845514.html