"use strict";
// let p = new Promise((resolve, reject)=>{
// resolve('成功了')
// })
// p.then((result) => {
// console.log(result)
// })
// console.log(p,Promise)
class Promise1 {
constructor(executor) {
this['[[PromiseStatus]]'] = "pending";
this['[[PromiseValue]]'] = undefined;
this.taskQueue = {
resolveQueue: [],
rejectQueue: [],
};
this.msgList = [];
if (typeof executor !== 'function') {
throw new Error("未传入函数");
}
else {
executor(this.resolve.bind(this), this.reject.bind(this));
}
}
resolve(info) {
if (this["[[PromiseStatus]]"] !== 'pending')
return;
this['[[PromiseStatus]]'] = 'resolved';
this["[[PromiseValue]]"] = info;
this.taskQueue.resolveQueue.forEach(item => {
item(info);
});
this.public(true);
}
reject(info) {
if (this["[[PromiseStatus]]"] !== 'pending')
return;
this['[[PromiseStatus]]'] = 'rejected';
this["[[PromiseValue]]"] = info;
this.taskQueue.rejectQueue.forEach(item => {
item(info);
});
this.public(false);
}
then(resolveFn, rejectFn) {
if (this["[[PromiseStatus]]"] !== 'pending')
return this;
this.taskQueue.resolveQueue.push(resolveFn);
rejectFn && this.taskQueue.rejectQueue.push(rejectFn);
return this;
}
catch(rejectFn) {
if (this["[[PromiseStatus]]"] !== 'pending')
return;
rejectFn && this.taskQueue.rejectQueue.push(rejectFn);
}
subscribe(target, callback) {
target.msgList.push(callback);
}
public(flag) {
this.msgList.forEach(callback => {
callback(flag);
});
}
static all(promiseArr) {
let p = new Promise1(() => { });
let index = 0;
for (let i = 0; i < promiseArr.length; i++) {
p.subscribe(promiseArr[i], (flag) => {
if (!flag) {
p.reject('失败了');
return;
}
if (flag) {
index++;
if (index === promiseArr.length)
p.resolve('全部成功了');
}
});
}
return p;
}
}
let p1 = new Promise1((resolve, reject) => {
console.log('开始请求接口');
setTimeout(() => {
reject('p2接口请求失败');
}, 3000);
});
let p2 = new Promise1((resolve, reject) => {
console.log('开始请求接口');
setTimeout(() => {
reject('p2接口请求失败');
}, 5000);
});
// p1.then( (result)=> {
// console.log(result)
// }).catch ( (result)=> {
// console.log(result)
// })
Promise1.all([p1, p2]).then((result) => {
console.log(result);
}).catch(result => {
console.log(result);
});
Promise实现
最新推荐文章于 2023-01-10 09:45:58 发布