Skip to content

Instantly share code, notes, and snippets.

@dtothefp
Last active December 6, 2015 02:55
Show Gist options
  • Save dtothefp/5b8b6794e9be5ef62eb8 to your computer and use it in GitHub Desktop.
Save dtothefp/5b8b6794e9be5ef62eb8 to your computer and use it in GitHub Desktop.
/**
* Thunk function returns a function that takes all args except the last `cb` that will return `err` or `data
* @param {Function} fn the function to wrap. ex. fs.readFile
* @param {Object|undefined} ctx the context to call the original `fn` with
* @return {Function} first function to be called with all args except the `cb`
* ex. const read = thunk(fs.readFile);
* const stuffFromTheCb = yield read('/path/to/cool/stuff.js');
*
* ex. const cp = child_process.spawn('./path/to/some/binary', ['--cool', 'stuff']);
* const cpEventThunked = thunk(cp.on, cp); //pass the child process as context or it breaks
* const closedCode = yield cpEventThunked('close');
*
* function returned doesn't take any arguments
* but we may want to do stuff after the async action happens
* ex. const startTunnel = thunk(browserStackTunnel.start, browserStackTunnel);
* try {
* yield startTunnel();
* } catch (err) {
* //do "whatevs" with the error
* }
*/
export default function(fn, ctx) {
//all arguments except the `cb`, maybe there will be 0 arguments
return (...args) => {
//if there are no args then just call the original function with the cb
return (cb) => {
fn.apply(ctx || null, args.length ? [...args, cb] : [cb]);
};
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment