class Promise2 {
succeed = null
fail = null
state = 'pending'
constructor(fn) {
fn(this.resolve.bind(this), this.reject.bind(this))
}
resolve(result) {
setTimeout(() => {
this.state = 'fulfilled'
this.succeed(result)
})
}
reject(reason) {
setTimeout(() => {
this.state = 'rejected'
this.fail(reason)
})
}
then(succeed, fail) {
this.succeed = succeed
this.fail = fail
}
}
Promise2.all = function(arrP) {
let list = []
return new Promise2((resolve, reject) => {
for(let i = 0; i < arrP.length; i++) {
arrP[i].then( data=> {
list[i] = data
list.length === arrP.length && resolve(list)
}, error => {
!hasErr && reject(error)
hasErr = true
})
}
})
}
Promise2.rac=function(arrP){
let hasVal = false
let hasError = false
return new Promise2((resolve, reject) => {
for(let i = 0; i < arrP.length; i++) {
arrP[i].then( data=> {
!hasVal&&!hasError&& resolve(list)
hasVal = true
}, error => {
!hasVal&&!hasError&& resolve(list)&& reject(error)
hasError = true
})
}
})
}
网友评论