Search code examples
javascriptpromisebluebird

Perform an intermediate action and carry over the previous result in bluebird


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 })

Solution

  • 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