Created
March 27, 2015 19:55
-
-
Save bnjbvr/a54828e75328d4922d89 to your computer and use it in GitHub Desktop.
Transform a (err, ..., callback) based function into a Promise-based function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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