JavaScript的:订购Ajax调用 [英] JavaScript : Ordering AJAX calls

查看:98
本文介绍了JavaScript的:订购Ajax调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个Ajax调用特定的功能。第三个呼叫依赖的前2个电话,即对第三呼叫前2个电话,同时必须完成。但前2 AJAX调用是独立的。所以,我想他们是异步和执行平行。

I have 3 ajax call for particular functionality. 3rd call is dependent of first 2 calls i.e. for the 3 rd call first 2 calls has to be finished. But first 2 AJAX calls are independent. So I want them to be async and execute parallely.

如何到现在组织这些电话?我试图把它们各自的呼叫成功嵌套块,但这种情况下,前2个电话也没有独立的。

How to structure these calls now? I tried to put them in nested success block of respective calls, but it that case first 2 calls are also not independent.

请建议一些须藤code,如果可能的话。

Kindly suggest with some sudo code, if possible.

推荐答案

使用承诺 $当

$.when(ajaxCall1(), ajaxCall2()).then(ajaxCall3);

其中, ajaxCallX 是这样

function ajaxCall1() {
    return $.ajax(...);
}

这基本上意味着后两者 ajaxCall1 的承诺及承诺 ajaxCall2 得到解决,执行功能 ajaxCall3

This basically means "after both, the promise of ajaxCall1 and the promise of ajaxCall2 are resolved, execute the function ajaxCall3".

这工作,因为返回的对象由 $。阿贾克斯(以及类似的方法)实现了诺言接口。更多信息也可以在 $。阿贾克斯文档发现

This works because the object returned by $.ajax (and similar methods) implements the promise interface. More information can also be found in the $.ajax documentation.

每个Ajax调用的响应被传递到然后回调作为参数。您可以访问它们作为

The responses of each Ajax call are passed to the then callback as arguments. You can acess them as

$.when(ajaxCall1(), ajaxCall2()).then(function(a1, a2) {
    // a1[0] is the response of the first call
    // a2[0] is the response of the second call
    ajaxCall3(a1[0], a2[0]);
});

有一个看 $。当文档的另一个例子。

Have a look at the $.when documentation for another example.

这篇关于JavaScript的:订购Ajax调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆