I\'m looking at this example from Angular\'s docs for $q
but I think this probably applies to promises in general. The example below is copied verbatim from the
When a promise is resolved/rejected, it will call its success/error handler:
var promiseB = promiseA.then(function(result) {
// do something with result
});
The then
method also returns a promise: promiseB, which will be resolved/rejected depending on the return value from the success/error handler from promiseA.
There are three possible values that promiseA's success/error handlers can return that will affect promiseB's outcome:
1. Return nothing --> PromiseB is resolved immediately,
and undefined is passed to the success handler of promiseB
2. Return a value --> PromiseB is resolved immediately,
and the value is passed to the success handler of promiseB
3. Return a promise --> When resolved, promiseB will be resolved.
When rejected, promiseB will be rejected. The value passed to
the promiseB's then handler will be the result of the promise
Armed with this understanding, you can make sense of the following:
promiseB = promiseA.then(function(result) {
return result + 1;
});
The then call returns promiseB immediately. When promiseA is resolved, it will pass the result to promiseA's success handler. Since the return value is promiseA's result + 1, the success handler is returning a value (option 2 above), so promiseB will resolve immediately, and promiseB's success handler will be passed promiseA's result + 1.