简体   繁体   English

使用Jquery $ when进行条件异步调用

[英]Making conditional Async calls using Jquery $when

I need to make two async ( Second call needs to be made only when some condition is true ) calls and when both the calls returns data, I need to make another call. 我需要进行两个异步( 仅当某些条件为true时才需要进行第二次调用 )调用,并且当两个调用都返回数据时,我需要进行另一个调用。 For this I decided to use jquery $when. 为此,我决定使用jquery $ when。

Before I make second Ajax call, I need to check some condition. 在进行第二个Ajax调用之前,我需要检查一些条件。 And if its true, then I need to make second ajax call otherwise, there is no need to make second ajax call. 如果它是真的,那么我需要进行第二个ajax调用,否则,就不需要进行第二个ajax调用。

Here is Pseudo-code 这是伪代码

 $.when($.get(url, function (result, status, xhr) {
        myresult = result;
    })),
    (
        //If XYZ === 10
          //Make second Ajax call only if condition is true

    ).then(function (r1, r2) {
        //DO something

     });

How can I achieve this ?? 我该如何实现? With Jquery or any other library ?? 使用Jquery或任何其他库?

Execute a function after two ajax requests are successful. 在两个ajax请求成功之后执行一个函数。

$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ).done(function( a1, a2 ) {

  //if both the calls are sucess then only you can reach here.
  //  inside this you can make your third ajax call.

  }
});
var first = $.ajax(...);
var second = (condition) ? $.ajax(...) : $.Deferred().resolve(); // ajax only on condition

$.when(first, second).then(function(res1, res2){
    // work with res1 and res2, res2 is undefined if no call was made
});

You can use ternary operator for second ajax call. 您可以使用三元运算符进行第二个ajax调用。 pass null value if condition is false as second parameter to $.when . 如果condition为false,则将null值作为$.when第二个参数传递。

Here is Pseudo-code 这是伪代码

$.when(
    //first ajax call ,
    (XYZ===10) ? //second ajax call 
               : null
       ).then(function (r1, r2) {
        //DO something

     });

Hope it helps. 希望能帮助到你。

Demo:- jsfiddle.net/NF2jz/5721 (try for a=0 and a=1) 演示: -jsfiddle.net/NF2jz/5721 (尝试a = 0和a = 1)

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

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