Skip to content

Instantly share code, notes, and snippets.

@sktt
Last active July 29, 2016 01:51
Show Gist options
  • Save sktt/4dc9568b745d0965ac5d56ed38680c8e to your computer and use it in GitHub Desktop.
Save sktt/4dc9568b745d0965ac5d56ed38680c8e to your computer and use it in GitHub Desktop.
Tiny promisify function
/**
* 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