Combining multiple jQuery ajax requests

I have the following code:

$.when(loadProjects())
    .then(function() {

        $.when.apply($, buildRequests(projects))
        .then(function(data) {

            $.when.apply($, vcsRequests(buildTypes))
            .then(function(data) {

                $.when.apply($, vcsDetailRequests(vcsRoots))
                .then(function(data) {
                    alert('done');
                });

            });

        });

    });

Each of the functions passed to when.apply () returns arrays of requests. I cannot make calls to buildRequests until the calls from loadProjects () end because they rely on the information received from these calls. Each call depends on the information returned by the previous call, so they should be in that order. I need to know when all calls are finished, so I can process the returned data.

Is there a cleaner way to approach this?

+5
source share
3 answers

yepnope.js. , , ajax.


, , , yepnope.js . , , , loadProjects() , when() . pipe() -

loadProjects().pipe(buildRequests).pipe(vcsRequests).pipe(vcsDetailRequests);

buildRequests():

function buildRequests(projects){
    // Do something using projects
    // ...

    var requestsPromise = ...; // Finally get ajax promise for requests
    return requestPromise;
}

requestPromise , /.


pipe():

// Example: Chain tasks: 

var request = $.ajax( url, { dataType: "json" } ),
    chained = request.pipe(function( data ) {
      return $.ajax( url2, { data: { user: data.userId } } );
    });

chained.done(function( data ) {
  // data retrieved from url2 as provided by the first request
});
+2

.... :

, . ... , ...

- :

PHP:
$projects = YourAPI::loadProjects();
$builds = YourAPI::getBuilds($projects);
$vcs = YourAPI::getVCS($builds);
$details = YourAPI::getVCSDetails($vcs);

// for example
return json_encode($details);

// OR, if you need all the data
$results = array( 
    "projects" => $projects,
    "builds" => $builds,
    "vsc" => $vcs,
    "details" => $details
);
return json_encode($results);

, HTTP;)

+1

AJAX request dependency chain: You can bind multiple AJAX requests - for example, the first call receives user user data, and we need to pass this value to the second script. Remember that it $.then()returns a new promise, which can then be passed to a method $.done()or another $.then().

var a1 = $.ajax({
             url: '/first/request/url',
             dataType: 'json'
         }),
    a2 = a1.then(function(data) {
             // .then() returns a new promise
             return $.ajax({
                 url: '/second/request/url',
                 dataType: 'json',
                 data: data.userId
             });
         });

a2.done(function(data) {
    console.log(data);
});
+1
source

All Articles