Skip to content

Instantly share code, notes, and snippets.

@rahulkumar66
Created December 1, 2018 11:07
Show Gist options
  • Save rahulkumar66/b4ab3706ac0275598e5ad24710f24483 to your computer and use it in GitHub Desktop.
Save rahulkumar66/b4ab3706ac0275598e5ad24710f24483 to your computer and use it in GitHub Desktop.
Basic promise implementation
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