Created
April 15, 2014 06:56
-
-
Save anthonyringoet/10708648 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<title>Naive promise implementation</title> | |
</head> | |
<body> | |
<button id="a-button">Click</button> | |
</body> | |
</html> |
This file contains hidden or 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(){ | |
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