Last active
December 31, 2015 18:38
-
-
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!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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