Created
December 2, 2012 05:15
-
-
Save pgoodman/4187056 to your computer and use it in GitHub Desktop.
Block execution until the callback to a function returns.
This file contains hidden or 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
| /// based off of: https://gist.github.com/1227319/957809d74d902a4d7fc44c44c946eeed38c1cd1b | |
| /// Need to be running this code somewhere inside of a Fiber. | |
| /// Block execution until a callback to some function is executed. | |
| /// | |
| /// Args: | |
| /// context: The object context of the function (which takes a | |
| /// callback) that is being called. | |
| /// callback: The callback argument to the current function. | |
| /// opt_CallbackContext: An optional object context to pass to the callback | |
| /// function. | |
| Function.prototype.WaitOnCallback = function(context, callback, opt_CallbackContext) { | |
| var that = this; | |
| var caller = Fiber.current; | |
| var fiber = Fiber(function() { | |
| that.apply(context, [function(/* args */) { | |
| var args = Array.prototype.slice.call(arguments, 1); | |
| opt_CallbackContext = opt_CallbackContext || callback; | |
| callback.apply(opt_CallbackContext, args); | |
| caller.run(); | |
| }]); | |
| }); | |
| process.nextTick(fiber.run.bind(fiber)); | |
| return Fiber.yield(); | |
| } | |
| /// Example use: | |
| function Database() { | |
| this.db_ = new Db("my_database_name", | |
| new Server(host, port, {auto_reconnect: true}, {}), | |
| {w: 1}); | |
| this.db_.open.WaitOnCallback(this.db_, function() { | |
| console.log("Connected to `my_database_name` database."); | |
| }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment