[英]jQuery deferred object chaining failing
为什么这段代码不起作用?
它应该在加载第 2 步之前等待第 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 step2 首先触发,因为它具有更短的延迟,并且您可以同时有效地触发两个 $.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
)
接受的答案并不完全正确。 它并没有真正链接承诺,因为:
$("#message").html( "message: " + response.text )
是一个同步函数,不返回承诺。 因此返回它返回的值不会创建一个承诺链。 它适用于这个例子,但随着你添加越来越多的承诺,你会遇到麻烦。
链接承诺的正确方法是返回承诺:
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 );
})
更新:根据评论, $.when() 在这里是不必要的,应该在组合多个 Promise 时使用。
$.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 );
})
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.