Created
August 1, 2014 20:40
-
-
Save aalavandhan/75d54b1a3e3fc67e6827 to your computer and use it in GitHub Desktop.
A Custom Promise
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
var Promise = function(){ | |
this.pending = []; | |
} | |
Promise.prototype = { | |
then: function(onResolve, onReject){ | |
this.pending.push({ | |
resolve: onResolve, | |
reject: onReject | |
}) | |
return this | |
}, | |
resolve: function(data){ | |
this.then = function(reject, resolve){ | |
resolve && resolve(data) | |
} | |
this.executePending('resolve', data) | |
}, | |
reject: function(data){ | |
this.then = function(reject, resolve){ | |
reject && reject(data) | |
} | |
this.executePending('reject', data) | |
}, | |
executePending: function(type, data){ | |
var p, i = 0 | |
while (p = this.pending[i++]) { | |
p[type] && p[type](data) | |
} | |
delete this.pending | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment