【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) => {
            //失败处理
        })
    }
相关推荐
小怪点点2 小时前
手写promise
前端·promise
minge1 天前
借助 Trae Builder 把 TypeScript 的碎片化学习记录整理成文档
typescript
骑着小黑马1 天前
从 Electron 到 Tauri 2:我用 3.5MB 做了个音乐播放器
前端·vue.js·typescript
ZengLiangYi2 天前
并发 401 下的 Token 刷新竞态:一个被低估的 Bug
typescript
willow2 天前
Promise由浅入深
javascript·promise
袋鱼不重2 天前
Typescript 核心概念
前端·typescript
刮涂层_赢大奖2 天前
我把 AI 编程 Agent 变成了宝可梦,让它们在像素风办公室里跑来跑去
前端·typescript·claude
时光不负努力3 天前
编程常用模式集合
前端·javascript·typescript
时光不负努力3 天前
ts+vue3开发规范
vue.js·typescript
时光不负努力3 天前
typescript常用的dom 元素类型
前端·typescript