用Jquery延迟调用多个ajax调用然后(3个并行调用然后再完成一个ajax调用)

时间:2016-09-05 13:04:02

标签: javascript jquery parallel-processing

我的要求是并行调用3 ajax调用,然后仅在完成3次调用时,我再请求一次Ajax调用。所以我能够通过以下这个来自CSS-trick

的Chris article来实现这个目标
`$.when(
  $.get("url1"), //goes in parallel
  $.get("url2"), //goes in parallel
  $.get("url3") //goes in parallel
).then(
  $.get("url4") // fires only on completion of 3 calls above.
);`

但我的代码stuructre就像

`$.when(
   threeCalls(){
   //this gives 3 ajax calls from here
})
.then(
   singlecall(){
   //this shoould be only called after 3 calls been successfull
})`

这样,它不会等待singlecall()等待threecalls()方法完成,所有来电(其中4个)都会进入并行/异步。< / p>

我应该如何实现这一目标?

2 个答案:

答案 0 :(得分:0)

下面的示例显示了如何使用带函数的顺序调用。

而不是:when(singleCall()),而不是when(singleCall);没有parantheses。或者,它将在promise解析之前执行该函数。

// just open up the network tab in your browser and see that
// first 3 urls will go in parallel in threeCalls,
// and then the last url will go in singleCall

function threeCalls() {
  console.log("calling urls in parallel...");
  return [ 
    $.get("http://jsonplaceholder.typicode.com/posts/1"),
    $.get("http://jsonplaceholder.typicode.com/posts/2"),
    $.get("http://jsonplaceholder.typicode.com/posts/3")
  ];
}

function singleCall(results) {
  console.log("single call is here");
  return $.get("http://jsonplaceholder.typicode.com/posts/4");
}

$.when.apply($, threeCalls())
 .done(singleCall)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 1 :(得分:0)

这将更具可读性和功能性 (不要在call4上使用括号)

var call1 = $.ajax({}),
    call2 = $.ajax({}),
    call3 = $.ajax({}),
    call4 = $.ajax({});

$.when( call1, call2, call3 )
 .then( call4 );