Following the suggestions from AngularJS validation and promises, I would like to chain confirmation dialogs and thus validate several steps at once.
Based on data provided by the user, an API call is made to see what all needs to be confirmed by the user. For each step that needs confirmation, prompt the user and let them decide whether to go to next step. If any step returns false, the whole chain should return false.
I've been reading a lot about async JS and promises, but I have to admit I am still fairly new to it. How to properly chain these to get a final true/false for all steps? Note that an API call is needed to determine what all needs to be shown to the user based on provided information, hence fetchSomeData() as first call in the chain.
Any help or suggestions will be greatly appreciated.
fetchSomeData = function() {
var deferred = $q.defer();
api.fetchData(param1, param2, param3)
.then(function(data) {
deferred.resolve(data.content);
}, api.errorHandler);
return deferred.promise;
}
// data = {condition1: false, condition2: true, condition3: true}
// display confirmation dialogs for step 2 and step 3, not step 1
confirmStep1 = function(data) {
if (data.condition1) {
return confirmDialogService.popConfirm('step1').then(function(confirmed) {
return confirmed;
}, function() {
return false;
});
} else {
return $q.when(true);
}
}
confirmStep2 = function(data) {
if (data.condition2) {
return confirmDialogService.popConfirm('step2').then(function(confirmed) {
return confirmed;
}, function() {
return false;
});
} else {
return $q.when(true);
}
}
confirmStep3 = function(data) {
if (data.condition3) {
return confirmDialogService.popConfirm('step3').then(function(confirmed) {
return confirmed;
}, function() {
return false;
});
} else {
return $q.when(true);
}
}
confirmSteps = function() {
return fetchSomeData()
.then(confirmStep1(data))
.then(confirmStep2(data))
.then(confirmStep3(data));
}
confirmSteps().then(function(allConfirmed) {
if (allConfirmed == true) {
doSomething();
} else {
return;
}
});