【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) => {
            //失败处理
        })
    }
相关推荐
miss5 分钟前
从零做一个可视化规则引擎:Vue3 递归条件树 + 双引擎结果对比
前端·vue.js·typescript
seowmt1 天前
结构化数据和自然语言描述哪个更管用?答案分场景
人工智能·google·typescript·go语言·schema
进击的明明1 天前
TypeScript速通笔记(上)
前端·面试·typescript
Orange_sparkle1 天前
langgraph快速入门
学习·ai·typescript·deepseek·claude code
FYKJ_20102 天前
springboot刑事案件管理系统03047-计算机课程设计、毕业设计
vue.js·spring boot·python·mysql·typescript·spark·django
用户0934077735142 天前
HarmonyOS WPS Open SDK 实践:从 HAR 集成到 OpenFileRequest 最小闭环
typescript·harmonyos
FYKJ_20102 天前
springboot雅集社区养老管理系统04456-计算机课程设计、毕业设计
vue.js·spring boot·python·mysql·typescript·spark·django
FYKJ_20102 天前
express皖美特色农产品网售系统53118-计算机课程设计、毕业设计
javascript·vue.js·spring boot·mysql·typescript·spark·express
FYKJ_20102 天前
springboot羽毛球场地管理系统00626-计算机课程设计、毕业设计
vue.js·spring boot·python·mysql·typescript·spark·django
FYKJ_20102 天前
django药饮个性化推荐系统54839-计算机课程设计、毕业设计
vue.js·spring boot·python·mysql·typescript·spark·django