Created
November 23, 2011 15:24
-
-
Save jed/1388949 to your computer and use it in GitHub Desktop.
turn an async function sync
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
// Usage: | |
// function asyncAdd(a, b, cb){ cb(a + b ) } | |
// | |
// var syncAdd = sync(asyncAdd) | |
// , sum = syncAdd(2, 2) | |
// | |
// assert(sum == 4) | |
// | |
// NOTE: | |
// this only works for functions that execute their callback before returning. | |
// an error will be thrown if the function does not callback in time. | |
function sync(fn, cb) { | |
function synced() { | |
var err, data, done | |
arguments[arguments.length++] = | |
function(e, d){ err = e; data = d; done = true } | |
fn.apply(this, arguments) | |
if (!done) throw new Error(fn.name + " did not respond in time.") | |
if (err) throw err | |
return data | |
} | |
if (cb) cb(null, synced) | |
else return synced | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment