Skip to content

Instantly share code, notes, and snippets.

@anthonyringoet
Created April 15, 2014 06:56
Show Gist options
  • Save anthonyringoet/10708648 to your computer and use it in GitHub Desktop.
Save anthonyringoet/10708648 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Naive promise implementation</title>
</head>
<body>
<button id="a-button">Click</button>
</body>
</html>
function Promise(){
this.callbacks = [];
this.resolved = false;
}
Promise.prototype.then = function(callback){
if(this.resolved){
callback(this.data);
}
else{
this.callbacks.push(callback);
}
}
Promise.prototype.resolve = function(data){
this.data = data;
var callback;
for(var i = 0; i < this.callbacks.length; i++){
callback = this.callbacks[i];
callback(data);
}
this.resolved = true;
}
// ===========
function doStuff(){
var promise = new Promise();
setTimeout(function(){
promise.resolve('timed out message');
}, 6000);
return promise;
}
var promise = doStuff();
promise.then(function(message){
console.log(message);
});
// ===========
var btn = document.getElementById('a-button');
btn.addEventListener('click', function(e){
promise.then(function(message){
console.log('from click event');
console.log(message);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment