初步完成异步处理
class myPromise {
static PENDING = 'PENDING';
static FULFILLED = 'FULFILLED';
static REJECTED = 'REJECTED';
constructor(handler) {
if (typeof handler !== 'function') {
throw new TypeError('Promise resolver undefinde is not a function')
}
// 接收resolve || reject的参数
this.params;
// 定义接收事件函数的队列
this.resolveEventList = [];
this.rejectEventList = [];
// 定义初始状态值
this.status = myPromise.PENDING;
// 调用回调
handler(this._resolve.bind(this), this._reject.bind(this))
}
_resolve(val) {
// 保证先执行then 让事件队列有值
setTimeout(() => {
// 3-1 更改状态
if (this.status !== myPromise.PENDING) return;
this.status = myPromise.FULFILLED;
this.params = val;
// 5-1 当resolve执行 调用事件队列中的函数
let handler;
while (handler = this.resolveEventList.shift()) {
handler(this.params);
}
})
}
_reject() {
// onmessage 是个微任务
window.addEventListener('message',_=>{
// 3-2 更改状态
if (this.status !== myPromise.PENDING) return;
this.status = myPromise.REJECTED;
// 5-2 当reject执行 调用事件队列中的函数
let handler;
while (handler = this.rejectEventList.shift()) {
handler(this.params);
}
})
window.postMessage("");
}
// 4 将then中的函数添加到对应的事件队列中
then(resolveSucc, rejectErr) {
if (typeof resolveSucc == 'function') {
this.resolveEventList.push(resolveSucc);
}
if (typeof rejectErr == 'function') {
this.rejectEventList.push(rejectErr);
}
}
}
进阶
增加 then 的连缀及优化
class myPromise {
static PENDING = 'PENDING';
static FULFILLED = 'FULFILLED';
static REJECTED = 'REJECTED';
constructor(handler) {
if (typeof handler !== 'function') {
throw new TypeError('Promise resolver undefinde is not a function')
}
// 接收resolve || reject的参数
this.params;
// 定义接收事件函数的队列
this.resolveEventList = [];
this.rejectEventList = [];
// 定义初始状态值
this.status = myPromise.PENDING;
// 调用回调
handler(this._resolve.bind(this), this._reject.bind(this))
}
_resolve(val) {
// onmessage 是个微任务
// 保证先执行then 让事件队列有值
window.addEventListener('message', _ => {
// 3-1 更改状态
if (this.status !== myPromise.PENDING) return;
this.status = myPromise.FULFILLED;
this.params = val;
// 5-1 当resolve执行 调用事件队列中的函数
let handler;
while (handler = this.resolveEventList.shift()) {
handler(this.params);
}
})
window.postMessage("");
}
_reject() {
window.addEventListener('message', _ => {
// 3-2 更改状态
if (this.status !== myPromise.PENDING) return;
this.status = myPromise.REJECTED;
// 5-2 当reject执行 调用事件队列中的函数
let handler;
while (handler = this.rejectEventList.shift()) {
handler(this.params);
}
})
window.postMessage("");
}
// 4 将then中的函数添加到对应的事件队列中
then(resolveSucc, rejectErr) {
// 实现无限.then
return new myPromise((resolve, reject) => {
// 保证返回的promise里 先执行then确保事件队列有值
function _resolveSucc(params) {
// then中的返回值当做下一次then的参数
let val = resolveSucc(params);
resolve(val);
}
function _rejectErr(params) {
let val = rejectErr(params);
reject(val);
}
if (typeof resolveSucc == 'function') {
this.resolveEventList.push(_resolveSucc);
}
if (typeof rejectErr == 'function') {
this.rejectEventList.push(_rejectErr);
}
})
}
}