Skip to content

Instantly share code, notes, and snippets.

@tilgovi
Created September 19, 2011 19:20
Show Gist options
  • Save tilgovi/1227319 to your computer and use it in GitHub Desktop.
Save tilgovi/1227319 to your computer and use it in GitHub Desktop.
Node.js call/cc function with fibers
/* This is the call-with-current-continuation found in Scheme and other
* Lisps. It captures the current call context and passes a callback to
* resume it as an argument to the function. Here, I've modified it to fit
* JavaScript and node.js paradigms by making it a method on Function
* objects and using function (err, result) style callbacks.
*/
Function.prototype.callcc = function(context /* args... */) {
var that = this,
caller = Fiber.current,
fiber = Fiber(function () {
that.apply(context, Array.prototype.slice.call(arguments, 1).concat(
function (err, result) {
if (err)
caller.throwInto(err)
else
caller.run(result)
}
))
})
process.nextTick(fiber.run.bind(fiber))
return Fiber.yield()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment