Skip to content

Instantly share code, notes, and snippets.

@jed
Created November 23, 2011 15:24
Show Gist options
  • Save jed/1388949 to your computer and use it in GitHub Desktop.
Save jed/1388949 to your computer and use it in GitHub Desktop.
turn an async function sync
// 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