我需要以同步方式进行三个 HTTP 调用,如何将数据从一个调用传递到另一个调用?
function first()
{
ajax()
}
function second()
{
ajax()
}
function third()
{
ajax()
}
function main()
{
first().then(second).then(third)
}
我尝试将 deferred 用于这两个函数,我想出了一个部分解决方案。我可以将它扩展为三个功能吗?
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 对象。
这些对象与 Promise 兼容,因此可以与 .then()
/.done()
/.fail()
/链接.always()
。
.then()
是您在这种情况下想要的,与问题中的完全一样。
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()
。
DEMO (使用 $.when('foo')
代替 $.ajax(...)
来交付已实现的 promise )。
关于javascript - 如何使用 jQuery promises 链接三个异步调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16026942/