Universal Callback => Promise Adapter
With Koa and ES7 async functions gaining prominence, the JavaScript world is poised to transition to promises. That means we need a sane way to promisify callback-based APIs. Rather than importing lots of different promisification wrappers for each API, this lib provides a single way to promisify every API.
Install
npm install ugly-adapter
Use
;...var data = await ;
This lib also exposes methods to make partial application easier. Which is useful if you want to re-use an adapted version of a function.
var read = adapt;var data1 = await ;var data2 = await ;
API
adapt()
Call a bare function: Useful when you don't think a function cares about this
.
// signaturevar promise =
adapt.method()
Call a method on an object: Useful when you think a function definitely cares about this
.
// signaturevar promise = adaptmethod<object> <string> ...args // user.authenticate(opts, callback) examplevar user = adaptmethoduser 'authenticate' userName: userName password: password
adapt.part()
Partially apply a bare function: // signaturevar fn = adapt
adapt.method.part()
Partially apply a method on an object: // signaturevar fn = adaptmethod // examplevar user = var authenticate = adaptmethod
A note about partial application.
You can basically move the )(
around willy-nilly.
// these behave identicallyvar promise = adaptvar promise = adaptcvar promise = adaptbcvar promise = adaptabc
adapt.promify(lib)
Promify a library: You can promisify entire library modules, such as fs
.
It will return an object with all the same properties and functions.
The functions have the same signature—sans callback—and return promises.
var adapt = callbackFs = fs = adapt; fs;
The above promifies every function in the fs
module.
If you only want to promify a subset of functions, declare them in a whitelist.
var adapt = callbackFs = fs = adapt; fs;fs;fslink...; // error, wasn't in the whitelist!
Async/Await Example
Now that we can convert callbacks to promises, we can write async functions everywhere.
{ let data = await ; data = JSON; return data;}
Any Promise
Ugly adapter uses any-promise promises. This is something you can safely ignore and everything works normally. However, if you want to polyfill/replace your environment's Promise for whatever reason, this allows you swap in whatever conforming Promise you want and this library will use it.