synchronize
Advanced tools
Comparing version 0.1.1 to 0.1.2
{ | ||
"name" : "synchronize", | ||
"main" : "./synchronize", | ||
"version" : "0.1.1", | ||
"version" : "0.1.2", | ||
"homepage" : "http://alexeypetrushin.github.com/synchronize", | ||
@@ -6,0 +6,0 @@ "dependencies" : { |
require('fibers') | ||
// Takes functino and returns its synchronized version. | ||
var synchronizeFunction = function(fn){ | ||
return function(){ | ||
// Ensuring it runs within Fiber. | ||
var fiber = Fiber.current | ||
if(!fiber) throw new Error("can't synchronize code not enclosed with fiber!") | ||
// Calling. | ||
Array.prototype.push.call(arguments, function(){ | ||
// Resuming fiber when callback finishes. | ||
fiber.run(arguments) | ||
}) | ||
fn.apply(this, arguments) | ||
// Pausing fiber and waiting for result from callback. | ||
var args = yield() | ||
if(args[0]) throw args[0] | ||
return args[1] | ||
} | ||
} | ||
// Turns asynchronous function into another pseudo-synchronous function. | ||
@@ -20,31 +41,7 @@ // When You call it it will sort of `wait` and return callback result as | ||
if(!fn) throw new Error("object " + first + " has no function " + second + "!") | ||
return synchronizeFunction(fn).bind(context) | ||
} else { | ||
context = null | ||
fn = first | ||
fn = first | ||
return synchronizeFunction(fn) | ||
} | ||
// Returning synchronized wrapper. | ||
return function(){ | ||
// Ensuring it runs within Fiber. | ||
var fiber = Fiber.current | ||
if(!fiber) throw new Error("can't synchronize code not enclosed with fiber!") | ||
// Callback waiting for result or error. | ||
var callback = function(){ | ||
fiber.run(arguments) | ||
} | ||
// Calling. | ||
Array.prototype.push.call(arguments, callback) | ||
if(context){ | ||
fn.apply(context, arguments) | ||
} else { | ||
fn.apply(this, arguments) | ||
} | ||
// Sort-of "waiting" for result from callback. | ||
var args = yield() | ||
if(args[0]) throw args[0] | ||
return args[1] | ||
} | ||
} | ||
@@ -51,0 +48,0 @@ |
Sorry, the diff of this file is not supported yet
176972
5580