来实现一下Promise
内部源码
//定义新的Promise类
class LxPromise{
constructor(fn) {
//将成功的事件函数集成在successList数组里
this.successList = [];
//这里将所有的失败函数集成到failList里
this.failList = []
//pending,fullfilled,rejected
this.state = "pending"
//传入的函数对象,(异步操作的函数内容)
//并且调用resolveFn()和rejectFn()方法
//将resolveFn/rejectFn和传入的func绑定
//resolve() => resolveFn()
//reject() => rejectFn()
fn(this.resolveFn.bind(this),this.rejectFn.bind(this))
}
//定义then方法,把传入的func压入list数组
then(successFn,failFn){
if(typeof successFn=='function'){
this.successList.push(successFn)
}
if(typeof failFn=='function'){
this.failList.push(failFn)
}
}
catch(failFn){
if(typeof failFn=='function'){
this.failList.push(failFn)
}
}
//声明resolve实现函数
resolveFn(res){
this.state = "fullfilled"
this.successList.forEach(function(item,index){
//将成功的事件循环调用
item(res)
})
}
//声明reject实现函数
rejectFn(res){
this.state = 'rejected'
//注册到的失败所有事件进行调用
this.failList.forEach(function(item,index){
item(res)
})
throw Error(res);
}
}
//******************LxPromise()构造结束*****************
开始调用
//参数
var fn = function(resolve,reject){
setTimeout(function(){
if(true){
//函数调用
resolve("老陈promise成功")
}else{
//函数调用
reject("老陈promise失败")
}
},1000)
}
//创建实例对象
var p1 = new LxPromise(fn);
//函数声明,和函数的具体操作
p1.then(function(res){
document.body.style.background = "greenyellow"
console.log("这是成功做的事情")
console.log(res)
})
p1.catch(function(res){
document.body.style.background = "pink"
console.log("这是失败做的事情")
console.log(res)
})
ok~实现!可能还不是很完整,不过旨在学习认清promise的实现和运作过程。
发表回复