Skip to content

Instantly share code, notes, and snippets.

@Rich-Harris
Created June 2, 2014 14:19
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Rich-Harris/fc2d60ef947b37556619 to your computer and use it in GitHub Desktop.
Save Rich-Harris/fc2d60ef947b37556619 to your computer and use it in GitHub Desktop.
promisify.md

Include this snippet to promisify any node function that uses the standard form:

var Promise = require( 'es6-promise' ).Promise,
    promisify;

promisify = (function ( slice ) {
	return function ( fn, context ) {
		return function () {
			var args = slice.call( arguments );

			return new Promise( function ( fulfil, reject ) {
				var callback = function ( err ) {
					if ( err ) return reject( err );
					fulfil.apply( null, slice.call( arguments, 1 ) );
				};

				args.push( callback );
				fn.apply( context, args );
			});
		};
	};
}( [].slice ));

Then use it like this:

var standard = function ( arg1, arg2, arg3, callback ) {
  // callback is eventually called with two arguments - an error
  // (if applicable) and the result;
};

var promisified = promisify( standard );

promisified( arg1, arg2, arg3 ).then( handleResult, handleErr );

You can optionally pass in a context:

var fs = require( 'fs' ),
    readFile = promisify( fs.readFile, fs );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment