After coming across some advice on AngularJS validation and promises, I am interested in creating a chain of confirmation dialogs to validate multiple steps at once.
By making an API call based on user input, we can determine what steps require confirmation from the user. For each step that needs confirmation, present the user with a prompt to decide whether to proceed to the next step. If any step returns false, the entire chain should return false.
While I have been learning about asynchronous JavaScript and promises, I still consider myself relatively new to this concept. How can I effectively chain these actions to obtain a final true/false result for all steps? Keep in mind that an API call is necessary to determine which information should be displayed to the user, hence the initial fetchSomeData() call in the chain.
Any assistance or recommendations on this matter would be greatly valued.
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, but 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;
}
});