Skip to content

Instantly share code, notes, and snippets.

@ivanoats
Forked from dhable/promise.js
Created February 20, 2014 23:45
Show Gist options
  • Save ivanoats/9125815 to your computer and use it in GitHub Desktop.
Save ivanoats/9125815 to your computer and use it in GitHub Desktop.
function promise() {
var listeners = [],
resolved = false,
data;
return {
isResolved: function() {
return resolved;
},
whenDone: function(cb) {
if(resolved)
cb(data);
else
listeners.push(cb);
},
resolve: function(d) {
resolved = true;
data = d;
listeners.forEach(function(cb) {
cb(data);
});
listeners = [];
}
};
}
// Sample usage
var p = promise();
//...
p.whenDone(function(data) {
// do something with the data
});
// ...
p.resolve(42);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment