Created
September 19, 2011 19:20
-
-
Save tilgovi/1227319 to your computer and use it in GitHub Desktop.
Node.js call/cc function with fibers
This file contains 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
/* 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