I took few hours to understand this concept. Just to share my sample created based on this video: https://www.youtube.com/watch?v=wA0gZ...
pre
//this is my promise test
var $q = Apperyio.get("$q"); // get the $q function
var defer = $q.defer(); // put function on a variable
function calc(x, y) { // our calc function just to have fun
Code: Select all
var q = $q.defer(); // create the pormise
var preocessCalc = (x + y); //do the calc
if (preocessCalc = 0) { //check if calc is positive
q.resolve(preocessCalc); // if so, return it and continue
} else {
q.reject("Stoped! Negative value found:" + preocessCalc); // else return a failure
}
return q.promise; // return the promise result
}
defer.promise //this is the promise that will hold to be called
.then(function(receivedValue) { //this is the function for 1st action. receivedValue receive 0 from defer.resolve
Code: Select all
console.log('1st action: current value is ' + receivedValue); // print the current value
return calc(receivedValue, 3); //this return will trigger calc and pass new result to next action
})
.then(function(receivedValue) { //this is the function for 2nd action. receivedValue received from 1st action return
Code: Select all
console.log('2nd action: Value received was:' + receivedValue); // print the current value
return calc(receivedValue, -6); //TEST HERE - change -6 to 6 to continue the sequence (preocessCalc is negative and will became positive). When negative the sequence stop here.
})
.then(function(receivedValue) { //this is the function for 3rd action. receivedValue received from 2nd action return
Code: Select all
console.log('3rd action: Value received was:' + receivedValue); // print the current value
return calc(receivedValue, 9); //this return will trigger calc and pass new result to next action if exist
})
.catch(function(fail){ //this is to handle errors in the sequence. If an error occur (from q.reject - in our case a negative value), the sequence stops.
$scope.fail = console.log(fail);
})
.finally(function(){ //this will be called in case of success or fail of the sequence
Code: Select all
console.log("Last action, no matter what!");
});
defer.resolve(0); // this trigger the promise sequence with initial value of 0 for our calcs /pre
No further help is required for now.