Bluebird has a promisifyAll function that "Promisifies the entire object by going through the object's properties and creating an async equivalent of each function on the object and its prototype chain."
It creates functions with a suffix Async
.
Is it possible to replace the old functions entirely? The replaced functions work just like the original functions with the addition that they also return a Promise, so I thought it should be safe to just replace the old functions entirely.
var object = {};
object.fn = function(arg, cb) { cb(null,1) };
Bluebird.promisifyAll(object);
object.fn // do not want
object.fnAsync // => should replace `object.fn`
There's an option to specify a custom suffix option but unfortunately it doesn't work for empty string
Bluebird.promisifyAll(object, {suffix: ''});
RangeError: suffix must be a valid identifier
The problem is that if it walks the prototype and places *Async
functions - you would need brand new copies of every object in the prototype chain which will likely fail since libraries return their own objects.
That is - if you're using Mongoose and you're getting a collection object - the library would not know to return the promisified version - you'd have your own copy of a promisified version but the library won't play nice with it. In addition, the library calls its own functions too and changing their signature would break a lot of internal code.
Of course, if you need this just one level deep and you don't care about the prototype and you're not concerned about internal calls - you can easily accomplish it:
Object.getOwnPropertyNames(object).forEach(function(key){
object[key] = Promise.promisify(object[key]);
});
It's important to understand that this is not the usual case though. There are other apporoaches (like making the function return a promise if you omit the callback) but in general they're not very reliable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With