Created
June 6, 2011 10:44
-
-
Save ybogdanov/1010061 to your computer and use it in GitHub Desktop.
Using ES6 coroutines for synchronous yielding of asynchronous stuff
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
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