Promise TS写法

本文介绍了如何使用TypeScript定义和实现Promise,包括Istate类型定义、Tresovle和Treject函数类型,以及resolvePromise方法处理链式调用时的环状引用问题。通过创建YQPromise类,深入理解Promise的工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值