Skip to content

Instantly share code, notes, and snippets.

@cowboy
Created April 14, 2012 15:52
Show Gist options
  • Save cowboy/2385351 to your computer and use it in GitHub Desktop.
Save cowboy/2385351 to your computer and use it in GitHub Desktop.
JavaScript Function#makeCallbackable
/*
* Function#makeCallbackable
*
* Copyright (c) 2012 "Cowboy" Ben Alman
* Licensed under the MIT license.
* http://benalman.com/about/license/
*/
Function.prototype.makeCallbackable = function() {
var fn = this;
return function callbackable() {
var result = fn.apply(this, arguments);
// If more args were specified than fn accepts, and the last argument is
// a function, let's assume it's an async "done" function and call it.
var length = arguments.length;
var done = arguments[length - 1];
if (length > fn.length && typeof done === 'function') {
done(result);
}
};
};
// An asynchronous function.
function async(a, b, done) {
done(a + b);
}
// A synchronous function.
function sync(a, b) {
return a + b;
}
var async2 = async.makeCallbackable();
var async3 = sync.makeCallbackable();
async(1, 2, console.log.bind(console));
// logs 3
async2(1, 2, console.log.bind(console));
// logs 3
async3(1, 2, console.log.bind(console));
// logs 3
@cowboy
Copy link
Author

cowboy commented Apr 14, 2012

Also see callbackify.

@mathiasbynens
Copy link

Aren’t the functions returned by makeAsync still synchronous? Of course, that’s fine if the goal is to just turn a given function into one with an async-like signature.

@cowboy
Copy link
Author

cowboy commented Apr 14, 2012

Derp. Changing it to Function#makeCallbackable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment