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] ),继续...