Fairly new to angular and promises in general and I felt like I was doing everything right, until I read about common promise anti-patterns. I also noticed my code was getting really difficult to follow and read.
BTW, using Angular's Q implementation.
In this chain, am I handling error correctly? Should I use catch instead? How would I do that? Can I make my code more succinct?
EDIT: Couldn't find a question that talked about how to handle conditional promises. All the other stackoverflow questions were very simple without any complex chaining like my example. Hope this question helps someone
function importantPromise(){
var deferred = $q.defer();
var importantVariable;
topLevelPromise().then(function(result) {
var secondResult = doSomeWork(result, importantVariable);
secondPromise(secondResult)
.then(function(result) {
deferred.resolve(result);
}, function(error) {
deferred.reject(error);
});
}, function(error) {
conditionalPromise(importantVariable)
.then(function(result) {
deferred.resolve(result);
}, function(error) {
deferred.reject(error);
});
});
return deferred.promise;
}
//Actually using the promise
importantPromise().then(function(result){
handleResult(result);
}, function(error){
handleError(error);
});