Created
December 1, 2018 11:07
-
-
Save rahulkumar66/b4ab3706ac0275598e5ad24710f24483 to your computer and use it in GitHub Desktop.
Basic promise implementation
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 CustomPromise(fn) { | |
this.chain = []; | |
this.onResolve = this.onResolve.bind(this); | |
this.onReject = this.onReject.bind(this); | |
fn(this.onResolve, this.onReject); | |
} | |
CustomPromise.prototype.then = function (fn) { | |
this.chain.push(fn); | |
return this; | |
} | |
CustomPromise.prototype.catch = function (fn) { | |
this.errorFn = fn; | |
return this; | |
} | |
CustomPromise.prototype.onResolve = function (resolvedValue) { | |
let storedValue = resolvedValue; | |
for (let i = 0; i < this.chain.length; i++) { | |
const fn = this.chain[i]; | |
try { | |
storedValue = fn(storedValue); | |
} catch (err) { | |
this.onReject(err); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment