Created
February 24, 2012 13:03
-
-
Save briancavalier/1900788 to your computer and use it in GitHub Desktop.
Turn callback-based functions into promise-based functions
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
var when = require('../when'); | |
// A test callback-based function | |
function callbackBased(value, callback, errback) { | |
setTimeout(function() { | |
(value ? callback : errback)(value); | |
}, 100); | |
} | |
function log(val) { | |
console.log('ok', val); | |
} | |
function err(val) { | |
console.log('ERR', val); | |
} | |
// Just to show expected behavior | |
callbackBased(1, log, err); | |
callbackBased(0, log, err); | |
// promisify takes a callback-based function and returns an | |
// equivalent function that returns a promise instead of using callbacks. | |
function promisify(func, callbackPos, errbackPos, progbackPos) { | |
var orig, initArgs; | |
orig = func; | |
// If you only supply the function, assume callback and errback | |
// will always be the last two params. | |
// If you supply positions, use them to inject callback/errback/progback | |
// into the args. | |
if(arguments.length === 1) { | |
initArgs = function(args, deferred) { | |
args.push(deferred.resolve); | |
args.push(deferred.reject); | |
return args; | |
} | |
} else { | |
initArgs = function(args, deferred) { | |
if(typeof callbackPos == 'number') { | |
args.splice(callbackPos, 0, deferred.resolve); | |
} | |
if(typeof errbackPos == 'number') { | |
args.splice(errbackPos, 0, deferred.reject); | |
} | |
if(typeof progbackPos == 'number') { | |
args.splice(progbackPos, 0, deferred.progress); | |
} | |
return args; | |
} | |
} | |
return function() { | |
var d = when.defer(); | |
orig.apply(null, initArgs(Array.prototype.slice.call(arguments), d)); | |
return d.promise; | |
} | |
} | |
var promiseBased = promisify(callbackBased); | |
promiseBased(1).then(log, err); | |
promiseBased(0).then(log, err); | |
promiseBased = promisify(callbackBased, 1, 2); | |
promiseBased(1).then(log, err); | |
promiseBased(0).then(log, err); | |
// Negatives work, but are wonky | |
promiseBased = promisify(callbackBased, -1, -1); | |
promiseBased(1, 2).then(log, err); | |
promiseBased(0, 2).then(log, err); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The difference is that it allows you to create a new promise-based function that other components can consume instead of a callback-based function. I think that has a couple advantages: