Reputation: 2715
Is there a shorthand which would allow to get the value of the Promise and push it forward the promise chain without explicitly returning it?
In other words, is there a shorthand syntax for the following in bluebird:
.then(result => { callSomething(result); return result })
Upvotes: 0
Views: 46
Reputation: 1
If your going to use this pattern often, why not make a generic method for it
Promise.prototype.skip = function skip(fn, onRejected) {
return this.then(value => Promise.resolve(fn(value)).then(() => value), onRejected);
};
Let's say your example callSomething
returns a promise
function callSomething(v) {
console.log('skip got', v);
// this promise will be waited for, but the value will be ignored
return new Promise(resolve => setTimeout(resolve, 2000, 'wilma'));
}
now, b using skip
, instead of then
, the incoming fulfilled value, in this case fred
, will just pass on the following then
, but AFTER the promise returned by callSomething
is fulfilled
Promise.resolve('fred').skip(callSomething).then(console.log); // outputs "fred"
However, it doesn't matter if callsomething
doesn't return a Promise
Upvotes: 1
Reputation: 3440
You can use the Comma operator inside your arrow function's body (without curly braces):
.then(result => (callSomething(result), result)
The comma operator
evaluates each of its operands (from left to right) and returns the value of the last operand.
So, result
is returned by expression:
(callSomething(result), result)
Then, the arrow function without curly braces, returns the value of the expression specified as its body. For this reason, result
is returned.
Upvotes: 1