版本一,构造函数
function MyPromise(fn = () => {}) {
// const this = {}
this.state = 'pending'
this.value = undefined
const resolve = (value) => {
if (this.state === 'pending') {
this.state = 'fulfilled'
this.value = value
}
}
const reject = (value) => {
if (this.state === 'pending') {
this.state = 'rejected'
this.value = value
}
}
this.then = (onFulfilled, onRejected) => {
switch (this.state) {
case 'fulfilled':
onFulfilled(this.value)
break
case 'rejected':
onRejected(this.value)
break
default:
onRejected(this.value);
}
}
try {
fn(resolve, reject)
} catch (e) {
reject(e)
}
}
版本二,class类
class MyPromise {
constructor (fn) {
this.state = 'pending'
this.value = undefined
let resolve = value => {
if (this.state === 'pending') {
this.state = 'fulfilled'
this.value = value
}
}
let reject = value => {
if (this.state === 'pending') {
this.state = 'rejected'
this.value = value
}
}
// 自动执行函数
try {
fn(resolve, reject)
} catch (e) {
reject(e)
}
}
// then
then(onFulfilled, onRejected) {
switch (this.state) {
case 'fulfilled':
onFulfilled(this.value)
break
case 'rejected':
onRejected(this.value)
break
default:
onRejected(this.value);
}
}
}
实例化执行
new MyPromise((resolve, reject) => {
console.log('in Promise...')
resolve(111)
}).then((val) => {
console.log('resolve', val)
}, (e) => {
console.log('rejected', e)
})