原本promise是这样调用的
let p = new Promise((resolve, inject) => {
setTimeout(() => {
resolve(111)
})
})
p.then((res) => {
console.log(res)
})
手写自定义promise
class Mypromise {
constructor(fncallback) {
this.state = 'padding'
this.value = ''
this.err = ''
fncallback(this.success.bind(this), this.fail.bind(this))
}
success(value) {
this.value = value
this.state = 'resolve'
this.then(this.cuccessm, this.file)
}
fail(err) {
this.err = err
this.state = 'inject'
this.then(this.cuccessm, this.file)
}
then(cuccessm, file = () => {}) {
if (this.state == 'resolve') {
cuccessm(this.value)
} else if (this.state == 'inject') {
fail(this.err)
} else {
this.cuccessm = cuccessm
this.fail = fail
}
return this
}
}
调用
new Mypromise((resolve, inject) => {
setTimeout(() => {
resolve(222)
})
}).then((res) => {
console.log(res)
})