Reputation: 705
I have four functions that must be done in a certain order. All but one of these functions do some asynchronous AJAX stuff in them, however they (necessarily) do other things too. So these are my own functions, which I've turned into deferred promise objects by doing this kind of thing:
function populateOfferSettings() {
return $.Deferred(function (deferred) {
//Whole bunch of stuff happens here, including async AJAX
deferred.resolve();
}).promise();
}
This actually works fine when combined with this:
populateOfferSettings().then(viewReady);
The problem arises when I have more than just two functions in play. In reality I have at least four. I tried the most intuitive solution that came to me and failed:
populateOfferSettings().then(populateSegmentationSettings).then(populateHousehold).then(viewReady);
For reasons I don't understand, all of those functions are executed but there's no waiting for the promises to complete — they just all fire off. So then I tried this, which actually works as expected and each function waits for the previous to resolve:
populateOfferSettings().then(function () {
populateSegmentationSettings().then(function () {
populateHousehold().then(function () {
viewReady();
});
});
});
This feels very verbose though, even if I write a helper function to simplify implementation. I also don't really understand why my initial attempt failed. Is there something I'm missing or is this as simple as I can get it?
Upvotes: 1
Views: 62
Reputation: 140228
In jQuery 1.7.1 .pipe
is always what you want. You might as well overwrite .then
with .pipe
since .then
is absolutely useless before jQuery 1.8.
populateOfferSettings()
.pipe(populateSegmentationSettings)
.pipe(populateHousehold)
.pipe(viewReady);
Upvotes: 1
Reputation: 190976
You should be able to just keep calling then
, but returning the next promise in the chain.
populateOfferSettings()
.then(function () { return populateSegmentationSettings(); })
.then(function () { return populateHousehold(); })
.then(function () { viewReady(); });
Upvotes: 3