Reputation: 192487
I am not asking about the fulfillment value of the promise.
Here I am asking about the return value of the then()
function. The specific thing I am concerned about is building lists of promises based on conditions, such as:
function operationThatReturnsPromise() {
var p = q.resolve({ prop1 : value1 })
.then(function(ctx) {.... return ctx;});
if (condition1) {
// which usage is required or preferred?
// 1. p = p.then() ?
p = p.then(function(ctx) { ..... return ctx; } );
// 2. p.then() ?
p.then(function(ctx) {... return ctx; });
}
return p;
}
Are they equivalent? The doc at Mozilla states
A new promise is returned, whose state evolves depending on this promise and the provided callback functions.
This seems to indicate the former (option 1) is preferred. Any guidance?
Upvotes: 2
Views: 161
Reputation: 4559
Just do the test, option 2 would not work. If you want a promise which resolve with ctx
, you have to return the return value of then(function(ctx) {... return ctx; })
. With option 2, this return value is lost forever.
By the way, please guys check the benchmarks of Q, and realize you should probably use bluebird, which is the only promise library I know which has really good performances.
Upvotes: 0
Reputation: 887453
You should always use option 1.
Promises are immutable; .then()
returns a new promise with the (eventual) result of the callback.
If you ignore its return value, you will never wait for the operation to finish, and, worse any failures will be silently swallowed.
Upvotes: 1