Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bluebird PromisifyAll without any Async suffix, i.e. replace the original functions possible?

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
like image 333
laggingreflex Avatar asked Jun 02 '15 16:06

laggingreflex


1 Answers

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.

like image 71
Benjamin Gruenbaum Avatar answered Nov 12 '22 10:11

Benjamin Gruenbaum