promise polyfill
v1.0 CustomePromise构造器定义,状态从pending变为fulfilled/rejected,并且不可逆
;(function(){
// 定义三种状态
const status = {
pending: 0, /*进行时*/
fulfilled: 1, /*成功*/
rejected: 2 /*失败*/
}
class CustomePromise {
constructor(func){
// 初始状态
this._status = status.pending
this._value = null; // 记录resolve函数传入的参数
this._error = null; // 记录reject函数传入的参数
this._handler(func)
}
// 接收外部传入的函数,调用外部传入的函数
_handler(func){
let done = false // 就是让函数值执行一次
func(
(value) => {
if( done ) return
done = true
// console.log(value)
this._resolve(value)
},
(error) => {
if( done ) return
done = true
// console.log(error)
this._reject(error)
}
)
}
_resolve(){
// 把状态改为成功,状态不可逆
this._status = status.fulfilled
}
_reject(){
// 把状态改为失败,状态不可逆
this._status = status.rejected
}
}
window.CustomePromise = CustomePromise
})()
v2.0 定义then方法,收集注册的成功状态或失败状态要执行的函数
基于观察者模式
;(function(){
// 定义三种状态
const status = {
pending: 0, /*进行时*/
fulfilled: 1, /*成功*/
rejected: 2 /*失败*/
}
class CustomePromise {
constructor(func){
this._status = status.pending // 初始状态
this._value = null // 记录resolve函数传入的参数
this._error = null // 记录reject函数传入的参数
this.resolveArr = [] // 收集成功状态要执行的函数
this.rejectArr = [] // 收集失败状态要执行的函数
this._handler(func)
}
// 接收外部传入的函数,调用外部传入的函数
_handler(func){
let done = false // 就是让函数值执行一次
func(
(value) => {
if( done ) return
done = true
// console.log(value)
this._resolve(value)
},
(error) => {
if( done ) return
done = true
// console.log(error)
this._reject(error)
}
)
}
_resolve(value){
// 修改状态需要异步,暂时用定时器替代
setTimeout(() => {
// 把状态改为成功,状态不可逆
this._status = status.fulfilled
this._value = value
// 执行所有成功的函数
this.resolveArr.forEach(item => {
item(this._value)
})
})
}
_reject(error){
// 修改状态需要异步,暂时用定时器替代
setTimeout(() => {
// 把状态改为失败,状态不可逆
this._status = status.rejected
this._error = error
// 执行所有失败的函数
this.rejectArr.forEach(item => {
item(this._error)
})
})
}
// 收集注册的成功状态或失败状态要执行的函数
_done(resolveFunc, rejectFunc){
// pending的时候收集
if( this._status === 0 ){
if( typeof resolveFunc === 'function' ){
this.resolveArr.push(resolveFunc)
}
if( typeof rejectFunc === 'function' ){
this.rejectArr.push(rejectFunc)
}
}
}
// 收集注册的成功状态或失败状态要执行的函数
then(resolveFunc, rejectFunc){
this._done(resolveFunc, rejectFunc)
}
}
window.CustomePromise = CustomePromise
})()