Skip to content

Instantly share code, notes, and snippets.

@ybogdanov
Created June 6, 2011 10:44
Show Gist options
  • Save ybogdanov/1010061 to your computer and use it in GitHub Desktop.
Save ybogdanov/1010061 to your computer and use it in GitHub Desktop.
Using ES6 coroutines for synchronous yielding of asynchronous stuff
function someAsyncFunction(param, callback) {
setTimeout(function(){
callback(null, param); // result
}, 100)
}
Function.prototype.sync = function(param) {
this(param, function(e, result) {
Fiber.run(result); // substitute result instead of yield, resume current Fiber
})
return yield;
}
// Async environment
// 1. call someAsyncFunction in nodejs style
someAsyncFunction(123, function(err, result){
if (err) return console.error(err);
console.log('result: ', result);
})
// 2. call someAsyncFunction in new super-puper-synchronous way
var result = someAsyncFunction.sync(123);
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment