Skip to content

Instantly share code, notes, and snippets.

@darius
Last active December 21, 2015 15:28
Show Gist options
  • Select an option

  • Save darius/6326461 to your computer and use it in GitHub Desktop.

Select an option

Save darius/6326461 to your computer and use it in GitHub Desktop.
// Not a serious or proper implementation of promises.
// I haven't even bothered to look at the JS promises spec, and I
// know it's missing error handling at the least.
// Seriously, don't use this: it's just the most straightforward
// code to run the benchmark below, and nothing else.
var agenda = [];
function eventLoop() {
var front = 0;
while (front < agenda.length)
agenda[front++]();
agenda = [];
}
function defer() {
var value;
var watchers = []; // (null after resolution)
var promise = {
then: function(f) {
var deferred = defer(), resolve = deferred.resolve;
var event = function() { resolve(f(value)); };
if (watchers === null)
agenda.push(event);
else
watchers.push(event);
return deferred.promise;
}
};
var resolve = function(resolution) {
if (watchers === null)
throw new Error("Multiple assignment to promise. Old: "
+ value + " New: " + resolution);
value = resolution;
watchers.forEach(function(watcher) { agenda.push(watcher); });
watchers = null;
};
return {
promise: promise,
resolve: resolve
};
}
// From http://swannodette.github.io/2013/08/23/make-no-promises/
function benchmark() {
var first = defer(), last = first.promise;
for (var i = 0; i < 100000; ++i)
last = last.then(function(val) { return val + 1; });
var start = Date.now();
first.resolve(0);
last.then(function(val) {
console.log("elapsed ms", Date.now()-start);
});
eventLoop();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment