手写Promise(简单)
2020-09-21 本文已影响0人
凛冬已至_123
Promise
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
}
}
Promise.all
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
})
}
})
}
Promise.race
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
})
}
})
}