class MyPromise {
constructor(executor) {
this.status = 'pending'
this.value = null
this.reason = null
this.onFulfilledArray = []
this.onRejectedArray = []
const resolve = (value) => {
// if (value instanceof Promise) {
// return value.then(resolve, reject)
// }
// 定义promise队列此实现方法并不稳定
setTimeout(() => {
this.value = value
this.status = 'fulfilled'
this.onFulfilledArray.forEach(func =>{
console.log(func)
func(value)
})
})
}
const reject = (reason) => {
// 定义promise队列此实现方法并不稳定
setTimeout(() => {
this.reason = reason
this.status = 'rejected'
this.onRejectedArray.forEach(func => func(this.reason))
})
}
try {
executor(resolve, reject)
} catch (e) {
reject(e)
}
}
then(onfulfilled, onrejected) {
// onfulfilled = typeof onfulfilled === 'function' ? onfulfilled : data => data
// onrejected = typeof onrejected === 'function' ? onrejected : error => error
// if (this.status === 'pending') {
// this.onfulfilledArray.push(onfulfilled)
// this.onfulfilledArray.push(onrejected)
// }
// if (this.status === 'fulfilled') {
// this.value = onfulfilled(this.value)
// }
// if (this.status === 'rejected') {
// onrejected(this.reason)
// }
// return this
onfulfilled = typeof onfulfilled === 'function' ? onfulfilled : data => data
onrejected = typeof onrejected === 'function' ? onrejected : error => error
// promise2 将作为 then 方法的返回值
let promise2
if (this.status === 'fulfilled') {
return promise2 = new Promise((resolve, reject) => {
setTimeout(() => {
try {
// 这个新的 promise2 resolved 的值为 onfulfilled 的执行结果
let result = onfulfilled(this.value)
resolve(result)
}
catch (e) {
reject(e)
}
})
})
}
if (this.status === 'rejected') {
return promise2 = new Promise((resolve, reject) => {
setTimeout(() => {
try {
// 这个新的 promise2 reject 的值为 onrejected 的执行结果
let result = onrejected(this.value)
resolve(result)
}
catch (e) {
reject(e)
}
})
})
}
if (this.status === 'pending') {
return promise2 = new Promise((resolve, reject) => {
this.onFulfilledArray.push(() => {
try {
let result = onfulfilled(this.value)
resolve(result)
}
catch (e) {
reject(e)
}
})
this.onRejectedArray.push(() => {
try {
let result = onrejected(this.reason)
resolve(result)
}
catch (e) {
reject(e)
}
})
})
}
}
}
const promise = new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve('data')
}, 1000)
// resolve('data')
//reject('error')
})
promise
.then((data) => {
console.log(data)
return data + '+next'
})
.then(data => {
console.log(data)
})
console