Last active
September 16, 2017 21:17
-
-
Save addnab/f2b183fa2395a39452f8754eb450cf68 to your computer and use it in GitHub Desktop.
My minimal 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
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