Optional first promise in the Angular chain

I have 2 $ http callers that return promises, but the first one is optional. I believe that I need to first create a promise using $q.defer() , but I missed something.

Here is my failed attempt:

 var p = $q.defer(); if (condition) { p = p.then(doOptionalFirst()); } return p.then(doOther()); 

What is the correct syntax for the chain of these two calls, with the first being optional?

+6
source share
1 answer

Use $q.when (or $q.resolve with AngularJS 1.4.1) to create an already resolved promise.

 var p = $q.resolve(); if (condition) { p = p.then(doOptionalFirst); } return p.then(doOther); 

If you are using deferred, you need to bind to .promise and then allow deferred at the appropriate time. In this case, you can assume that if condition true, deferred is automatically resolved. Thus, you can skip some additional, perhaps incomprehensible code, simply using promises already resolved.

+5
source

Source: https://habr.com/ru/post/989696/


All Articles