如何使用 jQuery 承诺链接三个异步调用? [英] How do I chain three asynchronous calls using jQuery promises?
问题描述
我需要以同步方式进行三个 HTTP 调用,如何将数据从一个调用传递到另一个调用?
I have three HTTP calls that need I need to make in a synchronous manner and how do I pass data from one call to the other?
function first()
{
ajax()
}
function second()
{
ajax()
}
function third()
{
ajax()
}
function main()
{
first().then(second).then(third)
}
我尝试对这两个函数使用 deferred 并想出了一个部分解决方案.我可以将其扩展为三个功能吗?
I tried to use the deferred for the two functions and I came up with a partial solution. Can I extend it to be for three functions?
function first() {
var deferred = $.Deferred();
$.ajax({
"success": function (resp)
{
deferred.resolve(resp);
},
});
return deferred.promise();
}
function second(foo) {
$.ajax({
"success": function (resp)
{
},
"error": function (resp)
{
}
});
}
first().then(function(foo){second(foo)})
推荐答案
在每种情况下,返回 $.ajax()
返回的 jqXHR 对象.
In each case, return the jqXHR object returned by $.ajax()
.
这些对象与 Promise 兼容,因此可以使用 .then()
/.done()
/.fail()
/链接.always()
.
These objects are Promise-compatible so can be chained with .then()
/.done()
/.fail()
/.always()
.
.then()
在这种情况下是你想要的,正如问题中一样.
.then()
is the one you want in this case, exactly as in the question.
function first() {
return $.ajax(...);
}
function second(data, textStatus, jqXHR) {
return $.ajax(...);
}
function third(data, textStatus, jqXHR) {
return $.ajax(...);
}
function main() {
first().then(second).then(third);
}
参数 data
、textStatus
和 jqXHR
来自前面函数中的 $.ajax()
调用, IE.first()
馈送 second()
和 second()
馈送 third()
.
Arguments data
, textStatus
and jqXHR
arise from the $.ajax()
call in the previous function, ie. first()
feeds second()
and second()
feeds third()
.
DEMO(使用 $.when('foo')
到交付已履行的承诺,代替 $.ajax(...)
).
DEMO (with $.when('foo')
to deliver a fulfilled promise, in place of $.ajax(...)
).
这篇关于如何使用 jQuery 承诺链接三个异步调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!