Last active
July 29, 2016 01:51
-
-
Save sktt/4dc9568b745d0965ac5d56ed38680c8e to your computer and use it in GitHub Desktop.
Tiny promisify function
This file contains hidden or 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
/** | |
* Promisify a node style async func. | |
* | |
* @param {function} f Function to with a node callback as its last argument. | |
* @param [{object}] scope Scope to run `f` in, if necessary. | |
* @return {Promise} | |
* | |
* @example ``` | |
* const read = promisify(fs.readFile, fs); | |
* read('./file') | |
* .then(data => console.log(data.toString('utf8'))) | |
* .catch(err => console.log(err)); | |
* ``` | |
*/ | |
const promisify = ((slice) => (f, scope) => function () { | |
return new Promise( | |
(res, rej) => f.apply( | |
scope, slice.call(arguments).concat( | |
(err, data) => err ? rej(err) : res(data) | |
) | |
) | |
); | |
} | |
)(Array.prototype.slice); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment