(function(window){
const PENDING='pending'
const RESOLVED='resolved'
const REJECTED='rejected'
//Promise构造函数
//excutor执行器函数
function Promise(excutor){
const that=this
that.status=PENDING//状态
that.data= undefined//数据
that.callbacks=[]//回调函数
function resolve(value){
if(that.status!==PENDING){
return
}
//改变状态为resolve
that.status=RESOLVED
//保存value数据
that.data=value
//如果有待执行的callback函数,立即异步执行回调函数
if(that.callbacks.length>0){
setTimeout(() => {//放入队列中执行所有成功的回调
that.callbacks.forEach(callbacksObj => {
callbacksObj.onResolved(value)
});
});
}
}
function reject(error){
if(that.status!==PENDING){
return
}
//改变状态为reject
that.status=REJECTED
//保存value数据
that.data=error
//如果有待执行的callback函数,立即异步执行回调函数
if(that.callbacks.length>0){
setTimeout(() => {//放入队列中执行所有成功的回调
that.callbacks.forEach(callbacksObj => {
callbacksObj.onRejected(error)
});
});
}
}
//立即同步执行执行器 函数
try {
excutor(resolve,reject)
} catch (error) {//如果执行器抛出异常,Promise对象变为失败
reject(error)
}
}
//Promise原型上的.then方法
//指定成功和失败的回调函数
//返回一个新的promise对象
Promise.prototype.then=function(onResolved,onRejected){
onResolved=typeof onResolved==='function'?onResolved:res=>res
onRejected=typeof onRejected==='function'?onRejected:error=>{throw error}
const that=this
return new Promise((resolve,reject)=>{
function handle(callback){
try {
const result = callback(that.data)
if (result instanceof Promise){
result.then(res=>{
resolve(res)
},error=>{
reject(error)
})
}else {
resolve(result)
}
} catch (error) {
reject(error)
}
}
if (that.status===PENDING) {
that.callbacks.push({
onResolved(value){
handle(onResolved)
},
onRejected(error){
handle(onRejected)
}
})
}else if(that.status===RESOLVED){
setTimeout(() => {
handle(onResolved)
});
}else{
setTimeout(() => {
handle(onRejected)
});
}
})
}
//Promise原型上的.catch方法
//指定失败的回调函数
//返回一个新的promise对象
Promise.prototype.catch=function(onRejected){
return this.then(undefined,onRejected)
}
//函数对象的resolve方法
Promise.resolve=function(value){
return new Promise((resolve,reject)=>{
if(value instanceof Promise){
value.then(resolve,reject)
}else{
resolve(value)
}
})
}
//函数对象的reject方法
Promise.reject=function(error){
return new Promise((resolve,reject)=>{
reject(error)
})
}
// Promise.all=function(promises){
// }
// Promise.race=function(promises){
// }
window.Promise=Promise
})(window)
06-07
568
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交