【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) => {
            //失败处理
        })
    }
相关推荐
随逸1771 小时前
《从零搭建NestJS项目》
数据库·typescript
唐璜Taro17 小时前
Vue3 + TypeScript 后台管理系统完整方案
前端·javascript·typescript
Wect18 小时前
LeetCode 530. 二叉搜索树的最小绝对差:两种解法详解(迭代+递归)
前端·算法·typescript
程序员林北北21 小时前
【前端进阶之旅】typescriot的数据类型讲解(二)
前端·javascript·vue.js·react.js·typescript
火车叼位21 小时前
TypeScript 类型体操:如何精准控制可选参数的“去留”
前端·typescript
却尘1 天前
你写的 TypeScript,其实只是穿了件类型外套的 JavaScript
前端·typescript
We་ct1 天前
LeetCode 102. 二叉树的层序遍历:图文拆解+代码详解
前端·算法·leetcode·typescript
We་ct1 天前
LeetCode 103. 二叉树的锯齿形层序遍历:解题思路+代码详解
前端·算法·leetcode·typescript·广度优先
折七2 天前
NestJS 用了两年,我换了这个
typescript·node.js·nestjs
Wect2 天前
LeetCode 102. 二叉树的层序遍历:图文拆解+代码详解
前端·算法·typescript