繁体   English   中英

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

[英]call multiple ajax call with Jquery deferred When and then(3 parallel calls and then on complete one more ajax call)

我的要求是并行调用3个Ajax调用,然后仅在完成3个调用后,再请求一个Ajax调用 因此,我能够通过CSS-trick的Chris的以下文章来实现这一目标

`$.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.
);`

但是我的代码结构就像

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

这样,它不会等待singlecall()等待threecalls()方法来完成,所有呼叫(其中4)变为并行/异步

我应该如何实现呢?

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

而不是: when(singleCall())when(singleCall)那样做; 没有括号。 或者,它将在承诺解决之前执行该功能。

 // 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> 

这将更具可读性和功能性(届时请勿在call4上使用括号)

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

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

暂无
暂无

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

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