【TS】promise代替回调函数使用

参考:

https://blog.csdn.net/a42626423/article/details/135101768

https://blog.csdn.net/a42626423/article/details/135101768

typescript 复制代码
    fun() {
        return new Promise((resolve, reject) => {
            let succ = Math.random() > 0.5
            setTimeout(() => {
                if (succ) {
                    resolve(null)
                }
                else {
                    reject(null)
                }
            }, 2000)
        });
    }


    test() {
        this.fun().then((data) => {
            //成功处理resolve
        }, (data) => {
            //失败处理reject
        })
        //或者

        this.fun().then((data) => {
            //成功处理
        }).catch((error: Error) => {
            //失败处理
        })
    }
    
    //加载多个
    fun2() {
        let loadArr = []
        return new Promise((resolve, reject) => {
            Promise.all(loadArr).then(() => {
                //loadArr都执行完之后
                resolve(null);
            }).catch((error: Error) => {
                //loadArr出错
                resolve(null);
            })
        });
    }

    //链式调用
    test2() {
        let p = new Promise(resolve => {
            setTimeout(() => {
                resolve("success 1")
            }, 2000)
        })

        p.then((info) => {
            // 此处继续返回一个promise对象,形成链式调用
            return new Promise(resolve => {
                console.log("info = ", info)
                setTimeout(() => {
                    resolve("success 2")
                }, 2000)
            })
        }).then((info) => {
            console.log("info = ", info)
        }).catch((error: Error) => {
            //失败处理
        })
    }
相关推荐
烬羽13 小时前
navigator.gpu 存在就够了?WebGPU 检测的两层陷阱
typescript·浏览器·全栈
触底反弹14 小时前
🚀 浏览器里跑 1.5B 参数大模型?我用 WebGPU + DeepSeek 做到了
人工智能·面试·typescript
退休倒计时17 小时前
【每日一题】LeetCode 20. 有效的括号 TypeScript
算法·leetcode·职场和发展·typescript
晓说前端19 小时前
TypeScript 核心语法应用 —— Vue 3 中的使用(上)
前端·typescript
渣波20 小时前
React Hooks 核心基石:深度解析 `useState` 的类型推断、泛型约束与空值安全
前端·typescript
YIAN20 小时前
吃透这 5 个核心点,你的 React+TS 代码直接上一个台阶
前端·react.js·typescript
meilindehuzi_a20 小时前
WebGPU DeepSeek项目实战(二):用单例模式加载Tokenizer并转发下载进度
单例模式·typescript·react
用户938515635071 天前
从零在浏览器里跑 DeepSeek-R1:WebGPU + Transformer.js 全链路实战
前端·设计模式·typescript
子兮曰1 天前
Bun vs Node.js 深度对决:跑分快 4 倍,真实业务只剩 3%,2026 年到底该怎么选?
前端·后端·typescript
水獭比特2 天前
Agent 的 timeout 为什么会失效?把一条总预算传到底
人工智能·typescript