Skip to content

Instantly share code, notes, and snippets.

@abrjagad
Created February 3, 2022 20:32
Show Gist options
  • Save abrjagad/e23f99a1850da7d0533f5669d9d9cb20 to your computer and use it in GitHub Desktop.
Save abrjagad/e23f99a1850da7d0533f5669d9d9cb20 to your computer and use it in GitHub Desktop.
promise polyfill
class Prom {
constructor(promiseCallback) {
this.state = "pending";
this.value = undefined;
this.calledResolve = false;
this.calledReject = false;
this.innerResolve = () => {};
this.innerReject = () => {};
promiseCallback(this.resolved.bind(this), this.rejected.bind(this));
}
resolved(value) {
this.calledResolve = true;
this.value = value;
this.then(this.innerResolve);
// debugger;
}
rejected(value) {
this.calledReject = true;
this.value = value;
this.fail(this.innerReject);
}
then(cb) {
if (this.calledResolve) {
this.innerResolve(this.value);
return;
}
this.innerResolve = cb;
return this;
}
fail(cb) {
if (this.calledReject) {
this.innerReject(this.value);
return;
}
this.innerReject = cb;
return this;
}
}
const promise = new Prom((resolve, reject) => {
setTimeout(() => {
resolve("We did it!");
}, 1000);
});
promise.then((response) => {
console.log(response);
});
promise.then((response) => {
console.log(response, "ave");
});
promise.fail((error) => {
console.log(error);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment