Promise A+ 规范封装练习,显示了then,catch,all和then链
封装自己的Promise
// ES6 CLASS 构造类
class Promise {
// constructor 指向的就是函数本身私有, 外面使用时,就直接new Promise() 创建实例
// 创建实例的时候,我们就把实例中传入的方法执行,所以excutorCallBack 进来就执行
constructor(excutorCallBack) {
// primise 进来就是pending状态,,,成功时fulfilled,失败时rejected
this.status = 'pending'
this.value = null;
// 用于存入then方法传入进来的方法
this.fulfilledAry = [];
this.rejectedAry = [];
//2、 执行excutorCallBack 成功或者失败只能执行一个,所以根据状态来进行控制
let resolveFn = (resolve) => {
let timer = setTimeout(() => {
clearTimeout(timer)
// 判断只有pending状态才可以进入
if (this.status !== 'pending') return
this.status = 'fulfilled';
this.value = resolve;
this.fulfilledAry.forEach(item => item(this.value))
}, 0)
};
let rejectFn = (reason) => {
let timer = setTimeout(() => {
clearTimeout(timer)
if (this.status !== 'pending') return
this.status = 'rejected';
this.value = reason;
this.rejectedAry.forEach(item => item(this.value))
}, 0)
}
//1、 处理异常
try {
excutorCallBack(resolveFn, rejectFn)
} catch (err) {
rejectFn(err)
}
}
// 原型方法写在constructor外面
then(fulfilledCallBack, rejectedCallBack) {
typeof fulfilledCallBack !== 'function' ? fulfilledCallBack = () => {
return this.value
} : null;
typeof rejectedCallBack !== 'function' ? rejectedCallBack = () => {
throw new Error(this.value)
} : null;
// 实现then链式写法
return new Promise((resolve, reject) => {
this.fulfilledAry.push(() => {
try {
let x = fulfilledCallBack(this.value);
x instanceof Promise ? x.then(resolve, reject) : resolve(x);
} catch (err) {
reject(err)
}
})
this.rejectedAry.push(() => {
try {
let x = rejectedCallBack(this.value);
x instanceof Promise ? x.then(resolve, reject) : resolve(x);
} catch (err) {
reject(err)
}
})
})
// // 这里使用了发布订阅模式
// this.fulfilledAry.push(fulfilledCallBack);
// this.rejectedAry.push(rejectedCallBack)
}
catch(rejectedCallBack) {
return this.then(null, rejectedCallBack)
}
//=>STATIC ALL
static all(promiseAry) {
return new Promise((resolve, reject) => {
let resultAry = [],
index = 0;
for (let i = 0; i < promiseAry.length; i++) {
promiseAry[i].then(result => {
index++;
resultAry[i] = result;
if (index === promiseAry.length) {
resolve(resultAry);
}
}).catch(reason => {
reject(reason);
});
}
});
}
}
module.exports = Promise
项目中使用自己的Promise
let Promise = require('./Promise');
// PROMISE A+ 规范练习
new Promise((resolve, reject) => {
console.log(1)
// throw new Error('NO')
setTimeout(() => {
resolve(100)
console.log(2)
}, 0)
}).then(res => {
console.log(res)
console.log(4)
}).catch(reson=>{
console.log(reson)
})
console.log(6)
// 结果:1,6,2,100,4