Angular conditional promises

For an angular project, I need to invest promises, and I encounter situations when I'm not sure what I'm doing. Here is one of my codes:

return Action1().then(function (data) { var defer = $q.defer(); if (data.condition) { $q.all([Action2(), Action3(), Action4()]).then(function () { defer.resolve(); }); } else { defer.reject("error_code"); } return defer.promise; }); 

Action1, Action2, Action3, and Action4 work with promises. These are many promises, and the actions depend on the conditions. Can I do this and be sure that my main function will always be solved or rejected?

I read that we can pass a promise inside the resolution function. Can I do this and this is the same as above:

 return Action1().then(function (data) { var defer = $q.defer(); if (data.condition) { defer.resolve($q.all([Action2(), Action3(), Action4()]); } else { defer.reject("error_code"); } return defer.promise; }); 
+5
source share
2 answers

No, it is not. Your first function will remain forever if one of Action2() , Action3() or Action4() made a “throw” and rejected the promise of $q.all(…) - your deferred will never be allowed. This is the most common deferred antipatter error you used here.

Your second function softens this, but is still overly complex. You don’t have to put it off at all! Just return the promise directly and use $q.reject :

 return Action1().then(function (data) { if (data.condition) { return $q.all([Action2(), Action3(), Action4()]); } else { return $q.reject("error_code"); } }); 

Or, since this happens inside the then handler, you can also use throw "error_code" .

+3
source

Thanks for your answer, I see my error in the first version of the code. I think it is q.all that bothers me.

I read the deferred antipattern. He said that we do not need to create deferred objects for no reason.

A simple case is the following:

  return Action1().then(function () { return $q.all([Action2(),Action3(), Action4()]); }); 

But due to if (data.condition) I cannot do this. Is my second code the only way to do this? Am I in some case, or should I use a respite?

It talks about a “promise”, but with Angular I don't know if this is good (libs seem unsupported).

Greetings

+1
source

All Articles