JSFiddle - React, Tailwind, and code Playground
by Vlad Rasenko
JavaScript
class _Promise {
constructor(handler) {
this.handler = handler
this._status = 'pending'
this._result = undefined
this.resolve = this.resolve.bind(this)
this.reject = this.reject.bind(this)
this.run()
}
get status () {
return this._status
}
set status (value) {
if (this.status !== 'pending') return
this._status = value
this.checkCurrentStatus()
}
run() {
setTimeout(() => {
try {
this.handler(this.resolve, this.reject)
} catch (err) {
this.reject(err)
}
})
}
resolve (value) {
this._result = value
this.status = 'fulfilled'
}
reject (err) {
this._result = err
this.status = 'rejected'
}
then (onFulfilled, onRejected) {
this.onFulfilled = onFulfilled
this.onRejected = onRejected
this.checkCurrentStatus()
}
checkCurrentStatus() {
switch (this._status) {
case 'fulfilled':
this.onFulfilled && this.onFulfilled(this._result)
break
case 'rejected':
this.onRejected && this.onRejected(this._result)
break
}
}
}
const p = new _Promise(res => setTimeout(() => res(true), 1000))
setTimeout(() => p.then(console.log), 2000)