简体   繁体   English

jQuery Deferred-向Deferred合同添加回调

[英]jQuery Deferred - Adding a callback to the Deferred contract

I'm trying to add another asynchronous call to the contract of an existing Deferred before its state is set to success. 我试图在其状态设置为成功之前,向现有的Deferred合同添加另一个异步调用。 Rather than try and explain this in English, see the following pseudo-code: 与其尝试用英语解释,不如参见下面的伪代码:

$.when(
    $.ajax({        
        url: someUrl,
        data: data,
        async: true,        
        success: function (data, textStatus, jqXhr) {
            console.log('Call 1 done.')
            jqXhr.pipe(
                $.ajax({        
                    url: someUrl,
                    data: data,
                    async: true,        
                    success: function (data, textStatus, jqXhr) {
                        console.log('Call 2 done.');
                    },       
                })
            );
        },       
    }),
    $.ajax({        
        url: someUrl,
        data: data,
        async: true,        
        success: function (data, textStatus, jqXhr) {
            console.log('Call 3 done.');
        },       
    })
).then(function(){ console.log('All done!'); });

Basically, Call 2 is dependent on the results of Call 1. I want Call 1 and Call 3 to be executed in parallel. 基本上,呼叫2取决于呼叫1的结果。我希望并行执行呼叫1和呼叫3。 Once all 3 calls are complete, I want the All Done code to execute. 完成所有3个调用后,我希望执行“所有完成”代码。 My understanding is that Deferred.pipe() is supposed to chain another asynchronous call to the given deferred, but in practice, I always get Call 2 completing after All Done. 我的理解是Deferred.pipe()应该将另一个异步调用链接到给定的延迟对象,但实际上,我总是在All Done之后完成Call 2。

Does anyone know how to get jQuery's Deferred to do what I want? 有谁知道如何让jQuery的Deferred来做我想做的事情? Hopefully the solution doesn't involve ripping the code apart into chunks any further. 希望该解决方案不会涉及将代码进一步撕成碎片。

Thanks for any help. 谢谢你的帮助。

UPDATE: Please see my follow up question . 更新:请参阅我的后续问题

You have to call .pipe on the deferred object returned by the first $.ajax call, not inside its success callback (this does not have any effect at all): 您必须在第一个$.ajax调用返回的延迟对象上调用.pipe ,而不是在其成功回调内部(这根本没有任何作用):

$.when(
    $.ajax({        
        // ...      
    }).pipe(function() {
        // return a deferred object from .pipe
        return $.ajax({        
            // ...      
        });
    }),
    $.ajax({        
        // ...       
    })
).done(function(){ console.log('All done!'); });

.pipe returns a new deferred object which only gets resolved once both, the original deferred object and the returned one get resolved. .pipe返回一个新的延迟对象,原始对象和返回的对象都只能解析一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM