Skip to content

Instantly share code, notes, and snippets.

@longnt80
Last active April 2, 2019 22:28
Show Gist options
  • Save longnt80/dac0b253611b414f2c368b07b4265a45 to your computer and use it in GitHub Desktop.
Save longnt80/dac0b253611b414f2c368b07b4265a45 to your computer and use it in GitHub Desktop.
Promise polyfill implementtion
class MyPromise {
constructor(cb) {
this.value;
this.state;
this.fulfilledCB = [];
this.rejecteddCB = [];
cb(this.resolve, this.reject);
}
then = (successCB, failureCB) => {
let nextVal;
if (successCB && this.fulfilledCB.indexOf(successCB) === -1) {
this.fulfilledCB.push(successCB);
}
if (failureCB && this.rejecteddCB.indexOf(failureCB) === -1) {
this.rejecteddCB.push(failureCB);
}
if (this.state === 'fulfilled') {
if (this.value && this.fulfilledCB.length > 0) {
nextVal = this.fulfilledCB.splice(0,1)[0](this.value);
if (this.fulfilledCB.length > 0) {
this.resolve(nextVal);
}
}
} else if (this.state === 'rejected') {
if (this.value && this.rejecteddCB.length > 0) {
nextVal = this.rejecteddCB.splice(0,1)[0](this.value);
if (this.rejecteddCB.length > 0) {
this.reject(nextVal);
}
}
}
return this;
}
resolve = (value) => {
if (this.state === 'rejected') return;
this.state = 'fulfilled';
this.value = value;
if (this.fulfilledCB[0]) {
this.then(this.fulfilledCB[0], null);
}
};
reject = (value) => {
if (this.state === 'fulfilled') return;
this.state = 'rejected';
this.value = value;
if (this.rejecteddCB[0]) {
this.then(null, this.rejecteddCB[0]);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment