I have 2 $http calls that return promises but the first one is optional. I believe that I have to first create a promise using $q.defer()
but I am missing something.
Here's my non working attempt:
var p = $q.defer();
if (condition) {
p = p.then(doOptionalFirst());
}
return p.then(doOther());
What is correct syntax to chain these 2 calls with the first being optional?
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 a deferred, you have to chain to the .promise
and then resolve the deferred at an appropriate time. In this case you can consider that if condition
is true the deferred is automatically resolved. Thus you can skip some extra possibly confusing code by just using an already resolved promise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With