polygoat
polygoat is a library to make functions support both callback and promise styles.
- no dependencies
- very small, < 30 lines of code
- no promise support/polyfill required
- simple, hack-free
- Node.js and browsers
- fast, see benchmark
Getting started
npm install polygoat
var pg = require("polygoat");
or
<script src="node_modules/polygoat/index.js"></script>
var pg = window.polygoat;
Usage
// wrap an asynchronous function with polygoat
function hybridReaddir(path, callback) {
return pg(done => {
fs.readdir(path, done);
}, callback);
}
// hybridReaddir can be used as a promise
hybridReaddir("/").then(console.log);
// or with a callback
hybridReaddir("/", console.log);
// or with async/await
(async () => {
console.log("listing...");
console.log(await hybridReaddir("/"));
console.log("done");
})();
// you can also pass the Promise implementation of your choice
var bluebird = require("bluebird");
function hybridReaddir(path, callback) {
return pg(
function(done) {
fs.readdir(path, done);
},
callback,
bluebird
);
}
hybridReaddir() instanceof bluebird; // true
Example
See example.js
Benchmark
npm run benchmark
Test
npm test
Goat icon by Agne Alesiute from the Noun Project