Call Multiple Functions Successively
Solution 1:
jQuery's ajax functions already return a promise. So you do not need to create new deferred objects if you are using jquery's ajax functions.
To get your functions called in succession: call the .then
method for however many functions you need to call. If one or more of your functions need to do some async task then just return a promise, the deferred object will wait to call the next then
callback till the returned promise resolves. Each then
callback will get passed the data returned in the previous then
(or in the case of returned promise the resolved data)
$.getJSON(rgUrl1,function(json1){
rgJson1 = json1; ...etc.
}).then(combineJason)
.then(divideArray)
.then(doOtherStuff);
//#2functioncombineJason(someData) {
//code to combine return $.getJSON("url to some other json endpoint");
}
//#3functiondivideArray(someData) {
//code to divide stuff //this function is sync so just return some datareturn someNewData;
}
//#4functiondoOtherStuff(someData) {
//code to do some other stuff//this function is async so return a promise;return $.getJSON("url to some other json endpoint");
}
JSFiddle Demostrating mixed async/sync succession
Solution 2:
To call them successively is quite easy, you don't need to wait for multiple async things but only for the previous one each.
You'd do
function getJason() {
return $.getJSON(rgUrl1);
}
function combineJason(json1) {
//code to combine
}
function divideArray() {
//code to divide stuff
}
function doOtherStuff() {
//code to do some other stuff
}
getJason().then(combineJason).then(divideArray).then(doOtherStuff);
which would be very similar to
doOtherStuff(divideArray(combineJason(getJason())));
only that it takes care to defer the computation (as a callback) if one result is asynchronous (in here, the $.getJSON
in getJason
).
Post a Comment for "Call Multiple Functions Successively"