Bluebird PromisifyAll without Async suffix, i.e. Replace original functions?

Bluebird has a promisifyAll function, which "Promotes the entire object by going through the properties of the object and creating the asynchronous equivalent of each function on the object and the prototype chain."

It creates functions with the suffix Async .

Is it possible to completely replace old functions? Replaceable functions work the same as the original functions, adding that they also return Promise, so I thought it was safe to just completely replace the old functions.

 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 is an option to specify a custom suffix parameter, but, unfortunately, it does not work for an empty string

 Bluebird.promisifyAll(object, {suffix: ''}); RangeError: suffix must be a valid identifier 
+6
source share
1 answer

The problem is that if it passes the prototype and hosts the *Async functions, you will need new copies of each object in the prototype chain, which are likely to fail as the libraries return their own objects.

That is - if you use Mongoose and you get a collection object - the library does not know to return the promised version - you will have your own copy of the promising version, but the library will not play well with this. In addition, the library also calls its own functions, and changing their signature will violate large internal code.

Of course, if you need it only one level, and you do not need a prototype, and you do not worry about internal calls, you can easily execute it:

 Object.getOwnPropertyNames(object).forEach(function(key){ object[key] = Promise.promisify(object[key]); }); 

It is important to understand that this is not an ordinary case. There are other apporoaches (for example, if a function returns a promise if you omit the callback), but in general they are not very reliable.

+5
source

Source: https://habr.com/ru/post/988396/


All Articles