我如何链使用jQuery承诺三种异步调用? [英] How do I chain three asynchronous calls using jQuery promises?
问题描述
我有需要,我需要以同步的方式进行,我如何从一个电话将数据传递给其他三个HTTP调用?
函数第一个()
{
阿贾克斯()
}第二个功能()
{
阿贾克斯()
}功能三()
{
阿贾克斯()
}
函数main()
{
第一()。然后(第二)。然后(第三)
}
我试图用推迟两个功能,我想出了一个部分解决方案。我可以延长它是三个功能?
函数第一个(){
变种推迟= $ .Deferred();
$阿贾克斯({ 成功:功能(RESP)
{ deferred.resolve(RESP);
}, });
返回deferred.promise();
}功能二(富){
$阿贾克斯({
成功:功能(RESP)
{
},
错误:功能(RESP)
{
}
});
}
第一个()。然后(功能(富){秒(富)})
在每一种情况下,返回由 $返回的jqXHR对象。阿贾克斯()
。
这些对象是无极兼容的,因此可以用。然后()
/ .done()
/被链接 .fail()
/ 。总是()
。
。然后()
是在这种情况下,想要的,正是因为在这一问题。
函数第一个(){
返回$阿贾克斯(...);
}第二个功能(数据,textStatus,jqXHR){
返回$阿贾克斯(...);
}第三个功能(数据,textStatus,jqXHR){
返回$阿贾克斯(...);
}函数main(){
。第一个(),然后(第二次)。然后(第三);
}
参数数据
, textStatus
和 jqXHR
从产生在previous功能 $。阿贾克斯()
通话,即得。 第()
供稿第二()
和第二()
提要第三()
。
演示 (用 $。当('富')
来提供一个兑现诺言,在 $的。阿贾克斯(...)
)。
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)
}
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)})
In each case, return the jqXHR object returned by $.ajax()
.
These objects are Promise-compatible so can be chained with .then()
/.done()
/.fail()
/.always()
.
.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);
}
Arguments data
, textStatus
and jqXHR
arise from the $.ajax()
call in the previous function, ie. first()
feeds second()
and second()
feeds third()
.
DEMO (with $.when('foo')
to deliver a fulfilled promise, in place of $.ajax(...)
).
这篇关于我如何链使用jQuery承诺三种异步调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!