上一次实现了一个简单的promise,这次继续写他的链式编程,仅仅是return出一个值的情况
特点
- promise的then方法会继续返回一个promise还能继续then
- 如果直接return一个值会在下一个then的成功处回调出来
- 有两种情况会在下一个失败的回调输出,一个是第一个then里面的方法报错了,还有一个是返回的一个promise里面的方法报错了。
const PENDING = 'PENDING'
const FULFILLED = 'FULFILLED'
const REJECTED = 'REJECTED'
class Promise {
constructor(executor) {
this.value = ''
this.reason = ''
this.status = PENDING
this.onFulfilledCBArr = []
this.onRejectedCBArr = []
executor(resolve.bind(this), reject.bind(this))
function resolve(params) {
this.status = FULFILLED
this.value = params
this.onFulfilledCBArr.forEach(fn => fn())
}
function reject(params) {
this.status = REJECTED
this.reason = params
this.onRejectedCBArr.forEach(fn => fn())
}
}
then(onFulfilledCB, onRejectedCB) {
return new Promise((resolve, reject) => {
if (this.status === FULFILLED) {
try {
let r = onFulfilledCB(this.value)
resolve(r)
} catch (error) {
reject(error)
}
}
if (this.status === REJECTED) {
try {
let r = onRejectedCB(this.reason)
resolve(r)
} catch (error) {
reject(error)
}
}
if (this.status === PENDING) {
this.onFulfilledCBArr.push(() => {
try {
let r = onFulfilledCB(this.value)
resolve(r)
} catch (error) {
reject(error)
}
})
this.onRejectedCBArr.push(() => {
try {
let r = onRejectedCB(this.reason)
resolve(r)
} catch (error) {
reject(error)
}
})
}
})
}
}
module.exports = Promise