【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) => {
            //失败处理
        })
    }
相关推荐
AI前端老薛16 小时前
TypeScript 内置工具类型全解析
typescript
Wect18 小时前
LeetCode 26.删除有序数组中的重复项:快慢指针的顺势应用
前端·typescript
踢球的打工仔20 小时前
typescript-基本类型
前端·javascript·typescript
ttod_qzstudio1 天前
TypeScript严格模式下的undefined与null
typescript·null·undefined
王林不想说话2 天前
React自定义Hooks
前端·react.js·typescript
咖啡の猫2 天前
TypeScript 开发环境搭建
前端·javascript·typescript
咖啡の猫2 天前
TypeScript基本类型
linux·ubuntu·typescript
Sheldon一蓑烟雨任平生2 天前
Vue3 低代码平台项目实战(上)
低代码·typescript·vue3·低代码平台·问卷调查·json schema
Hao_Harrision2 天前
50天50个小项目 (React19 + Tailwindcss V4) ✨ | AutoTextEffect(自动打字机)
前端·typescript·react·tailwindcss·vite7
Sheldon一蓑烟雨任平生2 天前
Vue3 低代码平台项目实战(下)
低代码·typescript·vue3·低代码平台·json schema·vue3项目