Created
October 29, 2021 20:18
MyPromise
This file contains hidden or 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
class MyPromise { | |
constructor(fn) { | |
this.status = 'PENDING'; | |
const resolve = (data) => { | |
if (this.status !== 'PENDING') return; | |
this.status = 'FULLFILLED'; | |
this.value = data; | |
this.onChange?.(); | |
}; | |
const reject = (data) => { | |
if (this.status !== 'PENDING') return; | |
this.status = 'REJECTED'; | |
this.value = data; | |
this.onChange?.(); | |
}; | |
try { | |
fn(resolve, reject); | |
} catch (err) { | |
reject(err); | |
} | |
} | |
then(onResolve, onReject) { | |
return new MyPromise((resolve, reject) => { | |
const map = { FULLFILLED: [onResolve, resolve], REJECTED: [onReject, reject] }; | |
const onChange = () => { | |
setTimeout(() => { | |
const [callback, fallback] = map[this.status]; | |
if (typeof callback !== 'function') { | |
fallback(this.value); | |
return; | |
} | |
try { | |
const result = callback(this.value); | |
result instanceof MyPromise ? result.then(resolve) : resolve(result); | |
} catch (err) { | |
reject(err); | |
} | |
}); | |
}; | |
if (this.status === 'PENDING') { | |
this.onChange = onChange; | |
} else { | |
onChange(); | |
} | |
}); | |
} | |
catch(onReject) { | |
return this.then(null, onReject); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment