Created
April 14, 2012 15:52
-
-
Save cowboy/2385351 to your computer and use it in GitHub Desktop.
JavaScript Function#makeCallbackable
This file contains hidden or 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
/* | |
* 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); | |
} | |
}; | |
}; |
This file contains hidden or 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
// 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.