Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional first promise in Angular chain

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?

like image 646
cyberwombat Avatar asked Jun 24 '15 20:06

cyberwombat


1 Answers

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.

like image 168
Explosion Pills Avatar answered Oct 28 '22 15:10

Explosion Pills