I don't quite understand magic deferred objects with jQuery. Assume the following code:
function callWebService(uri, filter, callback)
{
var data = {};
if (filter && filter != '')
data['$filter'] = filter;
jQuery.ajax({
url: '/_api/lists/' + uri + '/items',
data: data,
success: callback,
dataType: 'json'
});
}
function getInitialData() {
callWebService("InitialData", "", function (data) {
//do stuff with data
});
}
function getGreenData() {
callWebService("GreenData", "filter from InitialData", function (data) {
//do stuff with data
});
}
function getRedData() {
callWebService("RedData", "filter from InitialData", function (data) {
//do stuff with data
});
}
function getFinalData() {
callWebService("FinalData", "filter from RedData & GreenData", function (data) {
//do stuff with data
});
}
The order I want to do things is like so - in the end I will call four webservices whereas the calls depend on each other (one long chain):
- Call
getInitialData
- Call
getGreenData
with dependency ongetInitialData
- Call
getRedData
with dependency ongetInitialData
- Call
getFinalData
with dependencies ongetGreenData
andgetRedData
As you can tell 2 & 3 could happen simultaneously. I'm thinking I can use jQuery.when()
(or resolve
?), I just don't know how to apply it here. I think I need to rework the functions to always return the ajax object?
Pseude-code would look like this:
getInitialData().then(getGreenData, getRedData).then(getFinalData)
$.ajax returns a jQuery promise. You can then call
then
on that promise to chain completion to a function. The ajaxdata
is passed as the promise parameter to any final callback function. That is because $.ajax "promises to return the Ajax data".If you follow the same pattern for all your functions you can chain everything as you wanted. By not calling the functions, or adding anonymous callbacks, it simply uses the resulting promises from each function call and combines them together.
Something like:
To run promises in parallel, evaluate the functions immediately and let the resulting promises combine with
$.when
:e.g.
Hopefully this will give a better idea of how to pass data from one call to the next.
First a version of
callWebService()
that differs in that :$.ajax()
Now your four "get..." functions, which differ in that :
filter
parameter.then()
rather than passing it tocallWebService()
.getInitialData()
,getGreenData()
etc are called.Finally the master routine that controls the sequencing and data flow.
getAllSortsOfDependentData()
can now be called as follows, with the summary data available in the callback of a chained.then()
:That's the basics. In almost every function, various refinements are possible.