Skip to content

Instantly share code, notes, and snippets.

@bnjbvr
Created March 27, 2015 19:55
Show Gist options
  • Save bnjbvr/a54828e75328d4922d89 to your computer and use it in GitHub Desktop.
Save bnjbvr/a54828e75328d4922d89 to your computer and use it in GitHub Desktop.
Transform a (err, ..., callback) based function into a Promise-based function
function promisify(func) {
return function(...args) {
return new Promise(function(resolve, reject) {
func(...args, function(err, ...rest) {
if (err)
return reject(err);
resolve(...rest);
});
});
}
}
var fs = require('fs');
var popen = promisify(fs.open);
var pwrite = promisify(fs.write);
popen('./horse.js', 'w+').then(function(fd) {
return pwrite(fd, 'hello world');
}).then(function() {
console.log('all went smoothly');
}).catch(function(err) {
console.error('an error occurred');
console.error(err.tostring());
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment