Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chaining 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 into when.apply() return arrays of requests. I cannot perform the buildRequests calls until the calls from loadProjects() has finished as they rely on information returned from those calls. Each call depends on information returned by the previous call, so they must be in this order. I need to know when all the calls have finished so I can process the data returned.

Is there a cleaner way to approach this?

like image 942
JFoulkes Avatar asked Oct 09 '22 17:10

JFoulkes


1 Answers

I came across yepnope.js the other day. I haven't tried it myself yet, but it might be helpful if you're doing a lot of ajax loading.


Actually thinking this over makes me realize that yepnope.js is not really applicable to your case. What I would consider in your case is to have loadProjects() et al return a single promise by applying when() internally in each function. Also putting pipe() to use could lead to something like

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

Sample buildRequests():

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

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

The result of the requestPromise will then be passed into the next piped function once it is resolved/rejected.


From the docs on 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
});
like image 182
Supr Avatar answered Oct 12 '22 12:10

Supr