简体   繁体   中英

Breaking up promise chain

Why are these not equivalent and is there a way to make them so?

// Returns result of promiseB
var p = self.promiseA()
  .then(self.promiseB);
return p;


// Returns result of promiseA
var p = self.promiseA();
p.then(self.promiseB);
return p;

For example if I wanted to do something like:

var p = self.promiseA();

if(cond) {
  p.then(self.promiseB);
}
return p;

The first returns a combined promise (that will be resolved only when promiseA has been resolved and promiseB has been run).

In this first case, p is the result of running self.promiseA().then(); which is a new promise beyond just what self.promiseA() returns.


The second returns only the first promise which is only what self.promiseA() returns.


One thing that isn't always obvious with .then() is that we think of it like it runs later after the promise before is fulfilled, but that isn't really what happens. The entire .then() chain runs immediately. Function pointers are stored away to be called later (when promises are fulfilled), but the entire chain runs immediately and each call to .then() creates a new promise that can have different fulfillment timing and result than the previous one in the chain (it depends upon what each .then() callback does when it gets called).

So self.promiseA() doesn't return the same thing as self.promiseA.then(xxx) . The latter is a new promise that incorporates both the first promise and then result of running the .then() handler.


If you wanted to do your conditional, you could do this:

var p = self.promiseA();

if(cond) {
  p = p.then(self.promiseB);
}
return p;

If you're trying to return the accumulated or combined promise, then you need to return the result of p.then() , not just p .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM