简单版(无法链式调用)
const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'
function Promise(executor) {
var _this = this
this.onFulfilled = [] //事件订阅数组
this.onRejected = [] //事件订阅数组
this.state = PENDING
this.value = undefined
this.reason = undefined
function resolve(value) {
if (_this.state === PENDING) {
_this.state = FULFILLED
_this.value = value
_this.onFulfilled.forEach(fn => fn(value))
}
}
function reject(reason) {
if (_this.state === PENDING) {
_this.state = REJECTED
_this.value = reason
_this.onRejected.forEach(fn => fn(reason))
}
}
executor(resolve, reject)
}
Promise.prototype.then = function (onFulfilled, onRejected) {
if (this.state === FULFILLED) {
typeof onFulfilled === 'function' && onFulfilled(this.value)
}
if (this.state === REJECTED) {
typeof onRejected === 'function' && onRejected(this.value)
}
if (this.state === PENDING) {
typeof onFulfilled === 'function' && this.onFulfilled.push(onFulfilled)
typeof onRejected === 'function' && this.onRejected.push(onRejected)
}
}
let a = new Promise((resolve, reject) => {
console.log('Promise YES!')
setTimeout(() => {
resolve(1)
}, 1000)
})
a.then((res) => { console.log(res) }, (err) => { console.log(err) })
// Promise YES!
// 1