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?
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With