Last active
August 29, 2015 14:23
-
-
Save lilactown/27b287d563a43ce19bab to your computer and use it in GitHub Desktop.
ES6 denodeify
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
const denodeify = (fn) => | |
function (...args) { | |
// bind our node function to the current context with arguments | |
const boundFn = fn.bind(this, ...args); | |
return new Promise((resolve, reject) => { | |
// call our bound node-style function | |
// typical node-style is `callback (err, result)` | |
// but we can account for more arguments | |
// by using a spread | |
boundFn((err, ...results) => | |
// if an err, reject, otherwise resolve with results | |
(err) ? reject (err) : resolve (...results) | |
); | |
}); | |
}; | |
// Short version: | |
const denodeify = (fn) => function (...args) { | |
const boundFn = fn.bind(this, ...args); | |
return new Promise((resolve, reject) => { | |
boundFn((err, ...results) => (err) ? reject (err) : resolve (...results) ); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment