// 手写一个promise
function pro (executor){
let _this = this;
_this.$$status = 'pending'
_this.failCallback = undefined;
_this.successCallback = undefined;
_this.error = undefined ;
setTimeout(_=>{
executor(_this.resolve.bind(_this),_this.reject.bind(_this))
})
}
/**
* promise 的 .then
* .then 有两个参数,成功的回调函数及失败的回调
* .then() .catch 都是返回了一个新的promise对象
*/
/**
* promise 的链式调用
*/
pro.prototype.then = function(full,fail){
let newPromi = new pro(_=>{})
this.failCallback = fail;
this.successCallback = full
this.successDefer = newPromi.resolve.bind(newPromi)
this.failDefer = newPromi.reject.bind(newPromi)
return newPromi
}
pro.prototype.resolve = function (param){
let _this = this;
if (_this.$$status == 'pending'){
_this.$$status = 'success'
if (!_this.successCallback){
return
}
let result = _this.successCallback(param)
if (result && result instanceof pro){
result.then(_this.successDefer,_this.failDefer)
return ''
}
_this.successDefer(result)
}
}
pro.prototype.reject = function (){
let _this = this;
if (_this.$$status == 'pending'){
_this.$$status = 'fail'
if (_this.failCallback){
return
}
let result = _this.failCallback(param)
if (result && result instanceof pro){
result.then(_this.successDefer,_this.failDefer)
return ''
}
_this.failDefer(failDefer)
}
}
手写promise
最新推荐文章于 2025-01-29 18:46:46 发布