Created
March 24, 2011 09:28
-
-
Save ybogdanov/884795 to your computer and use it in GitHub Desktop.
fibers integration
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
/** | |
* Some existing external lib which you don't want to touch | |
*/ | |
var SomeModule = { | |
someAsyncFunction : function(callback) | |
{ | |
process.nextTick(function(){ | |
callback(null, 'result'); | |
}) | |
} | |
} | |
/** | |
* Your new module which you want to start develop using Fibers | |
*/ | |
var YourNewModule = { | |
// This method using fibers, but you want it to work | |
// normally with other ASYNC parts of your app - no problem | |
someSyncMethod : function() | |
{ | |
/*** FIBER ***/ | |
// Here you are already inside of a fiber! | |
// Here we use existing async lib, but in syncronous manner | |
// it's just as simple as Function.prototype.call() | |
var result = SomeModule.someAsyncFunction.sync(); | |
// some useful code of your module here ... | |
// and use any libs you want | |
// we use return instead of calling a callback | |
return 'ok'; | |
// or even throw an exception! | |
// it will go to a callback if you call this function from ASYNC environment | |
throw new Error('something went wrong'); | |
/*** END OF FIBER ***/ | |
}.async() // <-- here we make this function friendly with other async environment | |
} | |
// You ASYNC app code here: | |
// use your new module in normal asyncronous way | |
YourNewModule.someSyncMethod(function(err, result){ | |
if (err) return console.error(err); | |
console.log('result', result); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment