How to extend q.promise in node.js?

I need to extend q.promise with my own functions, I tried:

defer = q.defer();
defer.promise.prototype.funcName = function () {
    // my function
}

      

witch returns the following error:

TypeError: Cannot set property 'funcName' of undefined

      

How should I expand correctly q.promise

?


This is my actual problem: I need an alias for .then()

witch gets the name of the operation as an argument (instead of the function) and performs the operation according to the internal function library.

+3


source to share


1 answer


Q.makePromise

is the main function of Promise that you want to extend. As mentioned in the comments by @minitech and can be seen in the source

To create an alias, say " after

", then

all you have to do is:

Q.makePromise.prototype.after = Q.makePromise.prototype.then;

      

Then you can use .after

instead.then

defer = Q.defer();
defer.resolve(1);
defer.promise.after(console.log);
//=> 1

      



I need an alias for .then () witch gets the operation name as an argument (instead of a function) and performs that operation according to the internal function library.

This creates a function .do

that takes a string and displays it along with the value after the promise is resolved.

Q.makePromise.prototype.do = function(operation){
    return this.then(function(value){
        console.log('Do', operation, 'with', value);
    });
};

      

Then you can do

defer = Q.defer();
defer.resolve(1);
defer.promise.do('myoperation');
//=> Do myoperation with 1

      

+3


source







All Articles