jQuery 延迟对象链接失败

jQuery deferred object chaining failing

为什么这段代码不起作用?

加载步骤2.Currently前应等待步骤1加载,步骤2先触发。我正在使用 mockjax 来模拟​​ Ajax 调用。

$.mockjax({
    url: "/step1",
    responseTime: [3000, 4000],
    responseText: {
      status: "success",
      text: "Loading Step 1"
    }
});

$.mockjax({
    url: "/step2",
    responseTime: [100, 200],
    responseText: {
      status: "success",
      text: "Loading step 2"
    }
});


$.getJSON("/step1").then( function(response) {
    return  $("#message").html( "message: " + response.text );
})
.then(
    $.getJSON("/step2", function(response) {
            $("#message").html( "message: " + response.text );
    })                
)

getJSON 第 2 步首先触发,因为它的延迟更短,并且您实际上同时触发了两个 $.getJSON

试试这个

$.getJSON("/step1").then( function(response) {
    return  $("#message").html( "message: " + response.text );
})
.then(
    function() { // added this
        $.getJSON("/step2", function(response) {
            $("#message").html( "message: " + response.text );
        })         
    } // and added this
)

更新:根据评论,$.when() 在这里是不必要的,应该在寻求组合多个 Promise 时使用。

我建议使用 when - jsFiddle example here

    $.mockjax({
    url: "/step1",
    responseTime: [3000, 4000],
    responseText: {
      status: "success",
      text: "Loading Step 1"
    }
});

$.mockjax({
    url: "/step2",
    responseTime: [100, 200],
    responseText: {
      status: "success",
      text: "Loading step 2"
    }
});


$.when($.getJSON("/step1"))
    .then( function(data, textStatus, jqXHR) {
        $("#message").html( "message: " + data.text );
    })
    .then(
        $.getJSON("/step2", function(data, textStatus, jqXHR) {
            $("#message").html( "message: " + data.text );
    })                
)

接受的答案不太正确。它并没有真正链接承诺,因为:

$("#message").html( "message: " + response.text )

是同步函数,不是 return 承诺。因此 returning 其 return 的值不会创建承诺链。它适用于此示例,但随着您添加越来越多的承诺,您会遇到麻烦。

链接承诺的正确方法是 return 承诺:

someFunction().then(function(){return promise}).then(function(){});

因此对于您的示例,正​​确的链接方式是:

$.getJSON("/step1")
.then( function(response) {
    $("#message").html( "message: " + response.text );
    return $.getJSON("/step2"); // <-------------- return a promise!
})
.then(function(response){
    $("#message").html( "message: " + response.text );
})