es6、es7现在是前端开发工作中,不可缺少的技能之一。
es6中Promise大家也用的越来越频繁。
下面是一个手写简单的Promise。
class PromiseFn {
constructor(callback) {
this.status = 'pendding'
this.value = ''
this.reason = ''
this.callback = callback
this.handle()
}
resolve = (value) => {
if (this.status == 'pendding') {
this.value = value
this.status = 'resolve'
}
}
reject = (reason) => {
if (this.status == 'pendding') {
this.reason = reason
this.status = 'reject'
}
}
then = (resolve, reject = '') => {
if (this.status == 'resolve') {
resolve(this.value)
} else if (this.status == 'reject') {
// reject 有写,并且是一个函数
if (reject != '' && typeof reject == 'function') {
reject(this.reason)
}
}
return this
}
catch = (reject) => {
if (this.status == 'reject') {
// reject 有写,并且是一个函数
if (reject != '' && typeof reject == 'function') {
reject(this.reason)
}
}
return this
}
handle() {
this.callback(this.resolve, this.reject)
}
}
如有错误,请大家私密我。。。