Skip to content

Instantly share code, notes, and snippets.

@pgoodman
Created December 2, 2012 05:15
Show Gist options
  • Select an option

  • Save pgoodman/4187056 to your computer and use it in GitHub Desktop.

Select an option

Save pgoodman/4187056 to your computer and use it in GitHub Desktop.
Block execution until the callback to a function returns.
/// 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