【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) => {
            //失败处理
        })
    }
相关推荐
Shiy_11 小时前
用 TypeScript 验证三门问题:为什么换门胜率是 2/3?
算法·typescript
kkoral12 小时前
Vue3 图片标框功能实现方案
前端·vue.js·vscode·typescript
森G1 天前
TypeScript 基础类型
开发语言·typescript
烛阴1 天前
用 MCP 调教 AI 代理:让 Cocos Creator 3.8.8 核心逻辑一键全自动生成
typescript·cocos creator
Rain5092 天前
mini-cc 技术栈:跟着 Claude Code 先选 TypeScript + React + Ink
前端·javascript·react.js·typescript·node.js·ai编程
yantuguiguziPGJ2 天前
WeMed:一个医疗垂直领域大模型 问答系统的 Taro 小程序
typescript·node.js
tedcloud1232 天前
wifi-densepose部署教程:构建无线人体感知系统
服务器·javascript·网络·typescript·ocr
奇奇怪怪的问题2 天前
学习ts笔记(二):属性修饰符,泛型,接口
前端·typescript
阿正的梦工坊2 天前
【Typescript】04-数组元组枚举与字面量类型
javascript·ubuntu·typescript
狼丶宇先森2 天前
vue-sign-canvas v2 重构复盘:从 Vue 2 签名板到 Vue 3 + TypeScript 组件库
前端·vue.js·重构·typescript·开源软件·canvas