Optional first promise in Angular chain
Asked Answered
T

1

6

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?

Terena answered 24/6, 2015 at 20:43 Comment(0)
U
5

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.

Uncleanly answered 24/6, 2015 at 20:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.