Skip to content

Instantly share code, notes, and snippets.

@laverdet
Created March 12, 2011 04:50
Show Gist options
  • Save laverdet/867039 to your computer and use it in GitHub Desktop.
Save laverdet/867039 to your computer and use it in GitHub Desktop.
function Future() {}
Future.mixin({
didComplete: function(value) {
if (value === undefined) {
throw new TypeError('May not return undefined from future');
}
this._value = value;
var fibers = this._fibers;
if (fibers) {
delete this._fibers;
for (var ii = 0; ii < fibers.length; ++ii) {
fibers[ii].run(value);
}
}
},
didThrow: function(exception) {
if (!exception) {
throw new Error('Must throw non-empty exception!');
}
this._exception = exception;
var fibers = this._fibers;
if (fibers) {
delete this._fibers;
for (var ii = 0; ii < fibers.length; ++ii) {
fibers[ii].throwInto(exception);
}
}
},
resolve: function() {
if (this._exception) {
throw this._exception;
} else if (this._value !== undefined) {
return this._value;
} else {
this._fibers = this._fibers || [];
if (!Fiber.current) {
throw new Error('Can\'t resolve a future with no fiber!');
}
this._fibers.push(Fiber.current);
return yield();
}
},
});
function FiberFuture(fn) {
var that = this;
Fiber(function() {
try {
that.didComplete(fn());
} catch(e) {
that.didThrow(e);
}
}).run();
}
FiberFuture.inherit(Future);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment