【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) => {
            //失败处理
        })
    }
相关推荐
Czzzzlq2 小时前
【无标题】
typescript·node.js·ai编程
mobº4 小时前
Vue3 +TypeScript 项目总结
前端·javascript·typescript
用户056694948311 天前
🔥 我把 axios 接口封装,玩出了 NestJS 的感觉
typescript
索西引擎1 天前
【理论】TypeScript 函数重载:从 Vue 3 defineEmits 说起的类型安全实践
前端·typescript
漫游的渔夫1 天前
从 if-else 乱麻到状态机:前端开发者该怎么理解多 Agent 协作?
前端·人工智能·typescript
matrixmind81 天前
sindresorhustype-fest:TypeScript 工具类型集合
前端·javascript·其他·typescript
guangzan2 天前
DeepSeek-Lane:在 Cursor 内使用 DeepSeek V4 模型
typescript
晓杰'2 天前
从0到1实现 Balatro 游戏后端(1):项目规划与牌型判断实现
后端·websocket·typescript·node.js·游戏开发·项目实战·nestjs
Forget the Dream2 天前
基于适配器模式的 Axios 封装实践
设计模式·typescript·axios·适配器模式
烛衔溟3 天前
TypeScript 接口继承与混合类型
linux·ubuntu·typescript