function MyPromise(executorFn){
this.obj = {
state: 'pending'//'pending' // pending | fulfilled | rejected
}
this.thenCallback = null
this.thenResult = null
this.catchCallback = null
this.cathcError = null
const this_ = this
this.objProxy = new Proxy(this.obj, {
set: function (target, prop, value) {
console.log('proxy set');
if (prop !== 'state'){
return;
}
if (value ==='fulfilled'){
this_.thenCallback(this_.thenResult)
}else if (value ==='rejected'){
this_.catchCallback(this_.cathcError)
}
}
})
this.resolve = function (result) {
this_.thenResult = result
this_.objProxy.state = 'fulfilled'
console.log('this_.obj: ', this_.obj);
}
this.reject = function (error) {
this_.cathcError = error
this_.objProxy.state = 'rejected'
}
this.then = function (thenCallback) {
this_.thenCallback = thenCallback
return this_
}
this.catch = function (catchCallback) {
this_.catchCallback = catchCallback
}
executorFn(this.resolve, this.reject)
}
new MyPromise((resolve, reject)=>{
setTimeout(() => {
// resolve('done')
reject('error')
}, 500);
}).then(result => {
console.log('result: ', result);
}).catch(error =>{
console.log('error', error);
})
手撕Promise
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 咱们一起奋斗了这么长时间,终于揭开了 Promise 的真面目,是不是有种感觉:Promise 源码 乍一听很高深...
- 咱们书接上文( 点我查看[https://www.jianshu.com/p/565ad78b4b3b] ),继续...
- 咱们书接上文( 点我查看[https://www.jianshu.com/p/b16f412d5ba7] ),继续...
- 咱们书接上文( 点我查看[https://www.jianshu.com/p/5a03197461d8] ),继续...