In a promise library bluebird have function promisifyAll or other similar libraries that claim to convert async functions with callback patterns into promise based ie. resolve()
, reject()
, or done()
..So how does it work?
For example:
function myAsync1 (data, url, callBack) {...}
and if i put it in
Promise.promisify(myAsycn1);
then will my function work like this..
myAsync1('{..}', 'http://..').then(function(){...});
This is have been bothering me. Is there a pattern that async non promise libs or function need to follow for Bluebird promisifyAll to convert them to promises based methods or there is some magic that converts them.
If not then what are the requirements and how does it work with existing libraries like mongodb etc.
Yes, there is a pattern. The functions it converts must expect a callback as their last argument. Additionally, it must pass an error as the first argument to the callback (
null
if no error) and the return value as the second argument.The BlueBird
promisify
function is very difficult to follow because of optimizations, so I'll show a simple way it could be written:Now we could implement
promisifyAll
by looping over the functions in the target object and usingpromisify
on each one.The
promisifyAll()
method promisifies the entire module or object which is being called as a parameter. What it means is that a copy of each property of the object is created withAsync
suffix, which is actually a promisified version of the same method, i.e you can use the.then()
or.done()
methods on it .For example, if you have a
doSomething()
method insomeModule
module, after callingPromise.promisifyAll(someModule)
a new method will be created in the module calleddoSomethingAsync()
. You can use it this way:Check out the bluebird API documentation for more information.