Skip to content

Instantly share code, notes, and snippets.

@dhable
Last active December 31, 2015 18:38
Show Gist options
  • Save dhable/8027888 to your computer and use it in GitHub Desktop.
Save dhable/8027888 to your computer and use it in GitHub Desktop.
A quick promise implementation in JS to showcase how simple it is to implement a promise. Don't use in a production app!
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