type Istate = “pending” | “fulfilled” | “rejected”;
type Tresovle = (result?: any) => void;
type Treject = (reason?: any) => void;
type Tonfulfilled = (reason?: any) => YQPromise | any;
/**
*
* @param {
} res then里面的值
* @param {
} newPromise 返回的新promise
* @param {
} resolve
* @param {
} reject
*/
const resolvePromise = (x: YQPromise | any, newPromise: YQPromise | any, resolve: Tresovle, reject: Treject) => {
// 如果返回的promise等于自身
if (x === newPromise) {
console.error(“TypeError: Chaining cycle detected for promise #”);
reject(new TypeError(“Chaining cycle detected for promise # < Promise >”))
}
if (x !== null && (typeof x === 'object' || typeof x === 'function')) {
let called = false
try {
let then = x.then;
if (typeof then === "function") {
then.call(x, (y: any) => {
if (called) return;
called = true;
resolvePromise(y, newPromise, resolve, reject)
}, (err: any) => {
if (called) return;
called = true;
reject(err);
})
} else {
resolve(x);
}
} catch (error) {
if (called) return;
called = true;
reject(error)
}
} else {
resolve(x)
}
}
// 定义个Promise类
class YQPromise {
// 定义prmise的两个属性
private PromiseState: Istate = "pending";
private PromiseResult: any = undefined;
private callbacks: {
onfulfilled: (result: any) => void,
onrejected: (result: any) => void,
}[] = [];
// 构造函数接受一个函数
constructor(func: (resolve: (result: any) => void, reject: (result: any) => void) => any) {
this.PromiseState = "pending";
this.PromiseResult = undefined;
// 构造函数接收的一个参数,构造函数接受两个参数, 绑定this是因为函数自调用t