Skip to content

Instantly share code, notes, and snippets.

@addnab
Last active September 16, 2017 21:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save addnab/f2b183fa2395a39452f8754eb450cf68 to your computer and use it in GitHub Desktop.
Save addnab/f2b183fa2395a39452f8754eb450cf68 to your computer and use it in GitHub Desktop.
My minimal promise implementation
const PENDING = 0;
const FULFILLED = 1;
const REJECTED = 2;
class MyPromise {
constructor(fn) {
this.status = PENDING;
process.nextTick(() => {
fn(payload => {
this.status = FULFILLED;
this.result = payload;
}, err => {
this.status = REJECTED;
this.result = err;
})
});
return this;
}
then(fn) {
return this.onComplete(fn, FULFILLED);
}
catch(fn) {
return this.onComplete(fn, REJECTED);
}
onComplete(cb, status) {
return new MyPromise((resolve, reject) => {
const timer = setInterval(() => {
if (this.status === PENDING) {
return;
}
clearInterval(timer);
const statusMatch = this.status === status;
const errorFallThrough = !statusMatch && status === FULFILLED;
if (errorFallThrough) {
reject(this.result);
return;
}
if (!statusMatch) {
return;
}
try {
const r = cb(this.result);
resolve(r);
} catch(err) {
reject(err);
}
}, 1);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment